亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET(C#) Web Api通過文件流下載文件的實(shí)例

 更新時(shí)間:2016年06月23日 09:52:10   投稿:yourber  
這篇文章主要介紹了ASP.NET(C#) Web Api通過文件流下載文件的方法,提供源碼下載,需要的朋友可以參考下。

下載文件到本地是很多項(xiàng)目開發(fā)中需要實(shí)現(xiàn)的一個(gè)很簡單的功能。說簡單,是從具體的代碼實(shí)現(xiàn)上來說的,.NET的文件下載方式有很多種,本示例給大家介紹的是ASP.NET Web Api方式返回HttpResponseMessage下載文件到本地。實(shí)現(xiàn)的方法很簡單,其中就是讀取服務(wù)器的指定路徑文件流,將其做為返回的HttpResponseMessage的Content。直接貼出DownloadController控件器的代碼:

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;

namespace DownloadFileFromWebApi.Controllers
{
 [RoutePrefix("download")]
 public class DownloadController : ApiController
 {
 [Route("get_demo_file")]
 public HttpResponseMessage GetFileFromWebApi()
 {
  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);
  }
 }
 }
}

實(shí)現(xiàn)以上控制器后,我們可以直接打開這個(gè)api的地址(示例中的地址為:http://localhost:60560/download/get_demo_file),即可彈出下載文件的對(duì)話框了,如圖: asp-net-web-api-download-file 當(dāng)然,也可以直接通過示例項(xiàng)目首頁的下載鏈接體驗(yàn),點(diǎn)擊“下載示例文件”按鈕,將會(huì)彈出保存文件的提示。 好了,示例比較簡單,不用多說了。點(diǎn)擊這里下載示例源碼。

以上就是本文的全部內(nèi)容,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論