request to web client download file c# Call a Web API From a .NET Client (C#) This content is for a previous version of .NET. New development should use ASP.NET Core. For more information on using ASP.NET Core Web API, see: This tutorial shows how to call a web API from a .NET application, using System.Net.Http.HttpClient. In this tutorial, a client app is written that consumes the following web API: Action HTTP method Relative URI Get a product by ID GET /api/products/ id Create a new product POST /api/products Update a product PUT /api/products/ id Delete a product DELETE /api/products/ id. To learn how to implement this API with ASP.NET Web API, see Creating a Web API that Supports CRUD Operations. For simplicity, the client application in this tutorial is a Windows console application. HttpClient is also supported for Windows Phone and Windows Store apps. For more information, see Writing Web API Client Code for Multiple Platforms Using Portable Libraries. NOTE: If you pass base URLs and relative URIs as hard-coded values, be mindful of the rules for utilizing the HttpClient API. The HttpClient.BaseAddress property should be set to an address with a trailing forward slash ( / ). For example, when passing hard-coded resource URIs to the HttpClient.GetAsync method, don't include a leading forward slash. To get a Product by ID: Set client.BaseAddress = new Uri("https://localhost:5001/"); Request a Product . For example, client.GetAsync("api/products/4"); . Create the Console Application. In Visual Studio, create a new Windows console app named HttpClientSample and paste in the following code: The preceding code is the complete client app. RunAsync runs and blocks until it completes. Most HttpClient methods are async, because they perform network I/O. All of the async tasks are done inside RunAsync . Normally an app doesn't block the main thread, but this app doesn't allow any interaction. Install the Web API Client Libraries. Use NuGet Package Manager to install the Web API Client Libraries package. From the Tools menu, select NuGet Package Manager > Package Manager Console . In the Package Manager Console (PMC), type the following command: The preceding command adds the following NuGet packages to the project: .AspNet.WebApi.Client Newtonsoft.Json. Newtonsoft.Json (also known as Json.NET) is a popular high-performance JSON framework for .NET. Add a Model Class. Examine the Product class: This class matches the data model used by the web API. An app can use HttpClient to read a Product instance from an HTTP response. The app doesn't have to write any deserialization code. Create and Initialize HttpClient. Examine the static HttpClient property: HttpClient is intended to be instantiated once and reused throughout the life of an application. The following conditions can result in SocketException errors: Creating a new HttpClient instance per request. Server under heavy load. Creating a new HttpClient instance per request can exhaust the available sockets. The following code initializes the HttpClient instance: The preceding code: Sets the base URI for HTTP requests. Change the port number to the port used in the server app. The app won't work unless port for the server app is used. Sets the Accept header to "application/". Setting this header tells the server to send data in JSON format. Send a GET request to retrieve a resource. The following code sends a GET request for a product: The GetAsync method sends the HTTP GET request. When the method completes, it returns an HttpResponseMessage that contains the HTTP response. If the status code in the response is a success code, the response body contains the JSON representation of a product. Call ReadAsAsync to deserialize the JSON payload to a Product instance. The ReadAsAsync method is asynchronous because the response body can be arbitrarily large. HttpClient does not throw an exception when the HTTP response contains an error code. Instead, the IsSuccessStatusCode property is false if the status is an error code. If you prefer to treat HTTP error codes as exceptions, call HttpResponseMessage.EnsureSuccessStatusCode on the response object. EnsureSuccessStatusCode throws an exception if the status code falls outside the range 200–299. Note that HttpClient can throw exceptions for other reasons — for example, if the request times out. Media-Type Formatters to Deserialize. When ReadAsAsync is called with no parameters, it uses a default set of media formatters to read the response body. The default formatters support JSON, XML, and Form-url-encoded data. Instead of using the default formatters, you can provide a list of formatters to the ReadAsAsync method. Using a list of formatters is useful if you have a custom media-type formatter: Sending a POST Request to Create a Resource. The following code sends a POST request that contains a Product instance in JSON format: The PostAsJsonAsync method: Serializes an object to JSON. Sends the JSON payload in a POST request. If the request succeeds: It should return a 201 (Created) response. The response should include the URL of the created resources in the Location header. Sending a PUT Request to Update a Resource. The following code sends a PUT request to update a product: The PutAsJsonAsync method works like PostAsJsonAsync , except that it sends a PUT request instead of POST. Sending a DELETE Request to Delete a Resource. The following code sends a DELETE request to delete a product: Like GET, a DELETE request does not have a request body. You don't need to specify JSON or XML format with DELETE. Test the sample. To test the client app: Download and run the server app. Download instructions. Verify the server app is working. For example, http://localhost:64195/api/products should return a list of products. Set the base URI for HTTP requests. Change the port number to the port used in the server app. Don’t write your Web API Client code — you’re wasting your precious time. Web are heavily gaining traction in the software world, replacing the (good?) old Web Services. Virtually every API that is born today is likely to be REST and being built using frameworks like WCF (if you’re brave enough), ASP.NET MVC WebAPI or Spring. With this wide adoption of Web APIs, it’s important to provide the tools to make it efficient to work with these technologies. One particular case of efficiency is the ability to generate code whenever possible, in order to automate repetitive and no-brain-required tasks. is the new WSDL. If you’re old enough to remember Web Services, you’d know that W3C came up with the Description Language — or WSDL — which provides an XML-based description of the interface of the Web Service. WSDL is able to describe all the meta-data of a Web Service: operations, parameters, returns, complex objects, transaccional meta-data, etc. Although painful to be read by humans, WSDL has one awesome usage: Generating client code. Because REST APIs don’t come with such a description language, the community closed the gap and Swagger was born. Generating C# Web API Clients with NSwag. NSwag is an open source toolbox that, among other things, is able to generate C# and TypeScript client classes to consume Web APIs. It supports generating client code in the following scenarios: From ASP.NET Web API assembly by inspecting the assembly compiled by an ASP.NET Web API application or ASP.NET Core MVC; From Swagger specification either by reading the OpenAPI specification generated by Swagger or by generating it from the compiled assembly of the Web API; It also allows generating Open API specifications for ASP.NET Web API projects that do not use Swagger, which enables scenarios where users don’t want or can’t use Swagger. The documentation is very good and pretty extensive, but the following video is a good place to start: Using NSwag on a project. My test bed for NSwag was a small project I’m preparing for a training session, where I used NSwag to generate a C# Client for a Web API. Because the project is being built “as-we-go”, the interfaces of the Web API are subject to regular changes. So, I wanted to have simple way of re-generating the client code whenever the API contract was updated. Here’s the steps I took: Create a Class Library for your client code. I started by creating the Class Library that will receive the generated code and provide the client functionality. Pro tip: Always look to follow name conventions on your solutions. In this case, I named this Class Library with the suffix .Client to ensure that the purpose of this assembly is clear. For example, if your Web API project is named Foo.Bar.WebApi , the client assembly should be Foo.Bar.WebApi.Client . Creating .nswag project file. Then, I had to create my web-api-client.nswag file with NSwag Studio. This was pretty straight forward: Build the Solution to ensure the Web API DLLs are compiled; Select the .NET Assembly where the Web API Controllers are compiled into; Select which Controllers to generate client code from; On the “Outputs” pane, select the “CSharp Client” checkbox; Enter the namespace for the generated classes; At the end of the pane, enter the name of the file where client code will be generated — this file should in the directory of the .Client project; Click “Generate Files”; Et voila! The generated code for my beautiful Web API: Then I saved the .nswag file in the .Client Class Library and put it into source control, to make sure everyone is able to generate code using the same settings. Re-generating client code. Whenever changes are made to the API, it’s pretty simple to update the client code to reflect the new contract. I prefer to use the command line tool for this — it’s easier to automate and more direct than using the Studio. NSwag also ships with an MSBuild task which can be used to integrate code generation within a project’s build process. For that, I’ve used NSwag’s package for NPM which provides command line tools to perform several tasks. And that’s it! Client code generated in a matter of seconds. Next up… This was a very simple use case, so I’m actually eager to test NSwag on a real-world project. There are some still things I need to explore from this point on. The ones I’ve already identified are: Request to client download file c# i have created an application to post a file to my server (IIS 7, ASP.NET) i have try many way but it do nothing. while no exception return. this is the form of upload site. and the code for upload site (C#): I post it in browser ok, but when create post request using webrequest, nothing happend. here is the code: Please give me some direction to upload file. Answers. you can check for details of your need in this link : http://www.asp.net/web-forms/tutorials/data-access/working-with-binary-files/uploading-files- cs are you trying to load a file, store it somewhere ? you can use some physical drive in some server to store the files, i guess that would be easier. regards joon Hi, i want upload in an application, not . or you can have a textbox with a button, on click on the button read the file and upload the file using normal HttpWebRequest as you are doing. Download file with WebClient or HttpClient? I am trying to download file from a URL and I have to choose between WebClient and HttpClient. I have referenced this article and several other articles on the . Everywhere, it is suggested to go for HttpClient due to its great async support and other .Net 4.5 privileges. But I am still not totally convinced and need more inputs. I am using below code to download file from internet: WebClient: HttpClient: From my perspective, I can see only one disadvantage in using WebClient, that would be the non async call, blocking the calling thread. But what if I am not worried about the blocking of thread or use client.DownloadFileAsync() to leverage the async support? On the other hand, if I use HttpClient, ain't I loading every single byte of a file into memory and then writing it to a local file? If the file size is too large, won't memory overhead be expensive? Which could be avoided if we use WebClient, since it will directly write to local file and not consume system memory. So, if performance is my utter priority, which approach should I use for download? I would like to be clarified if my above assumption is wrong, and I am open to alternate approach as well. Download Files from Azure with .NET Core Web API and Blazor WebAssembly. In this article, we are going to learn how to download files from Azure using ASP.NET Core Web API as the server-side project and Blazor WebAssembly as the client-side. This article is a continuation of a previous one where we learned about uploading files to Azure. In that article, we also created Azure storage, so if you don’t have one created, you can do it following the instructions from the mentioned article. If you want to learn more about Blazor WebAssembly, we strongly suggest visiting our Blazor WebAssembly series of articles, where you can read about Blazor WebAssembly development, authentication, authorization, JSInterop, and other topics as well. We are going to divide this article into the following sections: Connecting ASP.NET Core Web API Project with Azure. In this article, we are going to create new projects for both the server and the client. That said, let’s create a new ASP.NET Core Web API project named DownloadAzure.Server . If we inspect our Azure storage created in the previous article, we are going to find a connection string that we require in our server app: We are going to use it in our appsettings.json file: Next, we have to install the Azure.Storage.Blobs library: After these actions, we have everything we need to connect to our Azure storage. Retrieving all the Files from the Azure Storage. Since we are going to have both the client-side and server-side applications, we will need a dto class to help us with the data transfer. So, let’s create a new class named BlobDto with the required properties: Of course, you can always expand the list of properties if you need more of them, but for our example, these three are quite enough. Now, in the Controllers folder, we are going to create a new BlobsController and implement an action to retrieve all the blobs from the Azure blob storage: In the constructor, we assign values to our private fields. We extract the connection string from the appsettings.json file and hardcode the container name since we know its name from the previous article. Of course, if you want, you can move that value to the appsettings.json file as well. We would even suggest that. Then, in the Get action, we create a new BlobDto list and create a reference to the Azure container using the connection string and the container name. Next, we iterate through all the blobs inside that container and extract required values into a new BlobDto object, which we store in a list. Finally, we return that list as a response to the client app. Testing. In the previous article, we have uploaded one file to the storage. But while preparing for this article, we have used the project from a previous one to upload two more files to our storage: So, you can do the same. Just visit the previous article and you will find the link to the source code of the project you can use to upload files. Now we can open Postman and send a single Get request to test our action: We can see our result returns three files with their names, URI, and ContentType properties. So, we have everything we need to display these files in our client application. Listing all the Files in the Blazor WebAssembly Application. First, let’s create a new Blazor WebAssembly application (don’t use the ASP.NET Core hosted option) named DownloadAzure.Client . After the creation, let’s modify the launchSettings.json file: Then, we have to modify the HttpClient configuration in the Program class: Lastly, we are going to modify the FetchData component to list all our files from Azure Storage: There is nothing complicated in this code. We just send the HTTP request as soon as our component initializes and once we get the response, we iterate through the list and display images on the page. One thing to note – for the sake of simplicity, we create a BlobDto class inside the component file. Since we have only one DTO object, this is just fine for the example. Of course, in real-world applications, you should create a shared project and place your shared files in it. That way, you don’t have to duplicate the same code in both projects. Before we test this, we have to enable CORS on the server-side project. So, let’s modify the ConfigureServices method in the Startup class: And also, add a single code line to the Configure method: Testing. Now, let’s start both apps, and navigate to the FetchData component: There we go, we can see all our files from the Azure storage. Now, we can implement the logic to download files from Azure with both Web API and Blazor apps. Download Files from Azure – Web API Part. Let’s start with a new DownloadController creation in the Controllers folder: After the initial logic, we can create our Download action: Here we start with the container reference. Then, we extract our blob by the name from that container. If the blob exists, we call the DownloadAsync method, which downloads the blob from the service including its metadata and properties. Next, we return the File to the client with the Content, ContentType, and the Name of the blob. If the blob doesn’t exist, we just return a bad request. That’s all it takes on the server-side. We can move on to the client app. Download Files from Azure – Blazor WebAssembly Logic. The first thing we are going to do is to modify the wwwroot folder by creating a new folder scripts and inside a new file downloadScript.js : We create a JavaScript function that accepts a single options object parameter. The options object will contain three properties: returned byte array from the server, blob’s name, and the content type. We are going to use this function to start the download on the client-side app, once it receives a response from a server. One more thing, we use the export keyword for this function since we are going to isolate this JS file as a separate module. You can learn more about reading the JavaScript functions in Blazor WebAssembly and the advantage of this approach in our How to Call JavaScript Functions with C# in Blazor WebAssembly article. Then, we have to modify the FetchData.razor file: In the HTML part, we just modify our img element by adding the onclick event and adding a new class to extract additional styling. The @code part contains the main changes. Since we have JavaScript logic, which we want to import as a module, we have to inject the IJSRuntime interface and create a private IJSObjectReference variable. Then in the OnInitializedAsync method, we import our file and store it as a module in our private variable. Again, you can learn much more about this in our How to Call JavaScript Functions with C# in Blazor WebAssembly article. Then in the Download method, we send an HTTP request that returns a byte array from the server. After getting the response, we call our download function from the js file and pass the required parameters as an object. Finally, we have to create an additional FetchData.razor.css file for our image styles: Testing. Let’s start both apps and navigate to the FetchData page. As soon as we hover over any picture, we are going to see the result of applied styles. Once we click on the picture, we are going to see the downloaded file: Everything works as expected. Conclusion. So, as you can see, with a few simple steps, we have achieved our goal for this article.