如何从Web API控制器返回文件? [英] How to return a file from web api controller?
本文介绍了如何从Web API控制器返回文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用MVC 5 Web Api控制器,并且我想返回一个文件:
I'm using a MVC 5 web Api Controller, and I want to return a file:
[Route("")]
public HttpResponseMessage GetFile()
{
var statusCode = HttpStatusCode.OK;
FileStream file = XLGeneration.XLGeneration.getXLFileExigence();
return Request.CreateResponse(statusCode, file);
}
它不起作用.
邮递员的例外是:
"ExceptionMessage":'ObjectContent`1'类型未能序列化内容类型为'application/json; charset = utf-8'的响应主体."
"ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
推荐答案
在其他人遇到麻烦的情况下,我正在发布对我有用的替代方法.
I'm posting what worked for me as an alternative in case anybody else is having trouble.
[ActionName("File")]
[HttpGet]
public HttpResponseMessage File()
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new System.IO.FileStream(yourFilePath, System.IO.FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return response;
}
这篇关于如何从Web API控制器返回文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文