猿问

如何在ASP.NET WebAPI中返回文件(FileContentResult)

如何在ASP.NET WebAPI中返回文件(FileContentResult)

在常规的MVC控制器中,我们可以用a输出pdf FileContentResult

public FileContentResult Test(TestViewModel vm){
    var stream = new MemoryStream();
    //... add content to the stream.

    return File(stream.GetBuffer(), "application/pdf", "test.pdf");}

但是我们怎样才能把它变成一个ApiController

[HttpPost]public IHttpActionResult Test(TestViewModel vm){
     //...
     return Ok(pdfOutput);}

这是我尝试过但它似乎不起作用。

[HttpGet]public IHttpActionResult Test(){
    var stream = new MemoryStream();
    //...
    var content = new StreamContent(stream);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    content.Headers.ContentLength = stream.GetBuffer().Length;
    return Ok(content);            }

浏览器中显示的返回结果为:

{"Headers":[{"Key":"Content-Type","Value":["application/pdf"]},{"Key":"Content-Length","Value":["152844"]}]}

有什么建议?


米琪卡哇伊
浏览 8512回答 3
3回答

杨__羊羊

所以,试试这个:控制器代码:[HttpGet]public&nbsp;HttpResponseMessage&nbsp;Test(){ &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;path&nbsp;=&nbsp;System.Web.HttpContext.Current.Server.MapPath("~/Content/test.docx");; &nbsp;&nbsp;&nbsp;&nbsp;HttpResponseMessage&nbsp;result&nbsp;=&nbsp;new&nbsp;HttpResponseMessage(HttpStatusCode.OK); &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;stream&nbsp;=&nbsp;new&nbsp;FileStream(path,&nbsp;FileMode.Open); &nbsp;&nbsp;&nbsp;&nbsp;result.Content&nbsp;=&nbsp;new&nbsp;StreamContent(stream); &nbsp;&nbsp;&nbsp;&nbsp;result.Content.Headers.ContentDisposition&nbsp;=&nbsp;new&nbsp;ContentDispositionHeaderValue("attachment"); &nbsp;&nbsp;&nbsp;&nbsp;result.Content.Headers.ContentDisposition.FileName&nbsp;=&nbsp;Path.GetFileName(path); &nbsp;&nbsp;&nbsp;&nbsp;result.Content.Headers.ContentType&nbsp;=&nbsp;new&nbsp;MediaTypeHeaderValue("application/octet-stream"); &nbsp;&nbsp;&nbsp;&nbsp;result.Content.Headers.ContentLength&nbsp;=&nbsp;stream.Length; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;result;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}查看Html标记(使用click事件和简单URL):<script&nbsp;type="text/javascript"> &nbsp;&nbsp;&nbsp;&nbsp;$(document).ready(function&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$("#btn").click(function&nbsp;()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;httproute&nbsp;=&nbsp;""&nbsp;-&nbsp;using&nbsp;this&nbsp;to&nbsp;construct&nbsp;proper&nbsp;web&nbsp;api&nbsp;links. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.location.href&nbsp;=&nbsp;"@Url.Action("GetFile",&nbsp;"Data",&nbsp;new&nbsp;{&nbsp;httproute&nbsp;=&nbsp;""&nbsp;})"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;});</script><button&nbsp;id="btn"> &nbsp;&nbsp;&nbsp;&nbsp;Button&nbsp;text</button><a&nbsp;href="&nbsp;@Url.Action("GetFile",&nbsp;"Data",&nbsp;new&nbsp;{&nbsp;httproute&nbsp;=&nbsp;""&nbsp;})&nbsp;">Data</a>
随时随地看视频慕课网APP
我要回答