Downloading files Locally is a very simple feature that needs to be implemented in many project development. Say simple, is from the concrete code realization come up to say,. NET files are downloaded in many ways, this example shows you how to return the Httpresponsemessage download file to the local Web API. The method of implementation is simple, which is to read the server's specified path file stream as the content of the returned httpresponsemessage. Directly post the code for the Downloadcontroller control:
Using System;Using System.Collections.Generic;Using System.IO;Using System.Linq;Using System.Net;Using System.Net.Http;Using System.Net.Http.Headers;Using System.Web.Http;Namespacedownloadfilefromwebapi.controllers{[Routeprefix ("Download")]PublicClassDownloadcontroller:Apicontroller {[Route ("Get_demo_file")]Public HttpresponsemessageGetfilefromwebapi () {try {var FilePath = System.Web.Hosting.HostingEnvironment.MapPath (@ "~/download/editplus64_xp85.com.zip");var stream = new FileStream (FilePath, FileMode.Open); Httpresponsemessage response = new httpresponsemessage (Httpstatuscode.ok); response. Content = new streamcontent (stream); response. Content.Headers.ContentType = new mediatypeheadervalue ( " Application/octet-stream "); Response. Content.Headers.ContentDisposition = new contentdispositionheadervalue (" attachment ") {Filename=" Wep Api Demo File.zip "}; return response;} catch {return new Httpresponsemessage (httpstatuscode.nocontent); } } }}
After implementing the above controller, we can open the address of this API directly (the address in the example is: Http://localhost:60560/download/get_demo_file), can pop up the download file dialog box, of course, You can also directly through the sample project first page of the download link experience, click the "Download sample Files" button, will pop up the prompt to save the file. Well, the example is quite simple, so don't say much. Click here to download the sample source code.
The ASP. NET (C #) Web API uses a file stream to download files to an on-premises instance