[英]Controller returning HttpResponseMessage not setting content type correctly
I have the following code in a controller to return a stream which is an Excel File to download on the client side: 我在控制器中有以下代码来返回流,该流是要在客户端下载的Excel文件:
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
MemoryStream memStream = ReportExporter.ExportReport(analystReport);
response.Content = new StreamContent(memStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = saveAsFileName;
return response;
When I make the request on the client side it simply gives me back the wrapper of the response message: 当我在客户端发出请求时,它只是将响应消息的包装返回给我:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Content-Type: application/octet-stream
Content-Disposition: attachment; filename=.xlsx
}
I believe this maybe due to the headers coming back as text as this is what I see in Chrome: 我相信这可能是由于标题以文本形式返回的原因,这就是我在Chrome中看到的内容:
Content-Type:text/html; charset=utf-8
I can't work out what is happening here having tried various things. 我尝试了各种各样的事情后无法弄清楚这里发生了什么。
Try this solution: 试试这个解决方案:
// Copy file to byte array
byte[] file = new byte[memStream.Length];
memStream.Read(file, 0, file.Length);
// Send file
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "inline;filename=" + saveAsFileName);
Response.Buffer = true;
Response.Clear();
Response.BinaryWrite(file);
Response.End();
// Return success
return new HttpStatusCodeResult(HttpStatusCode.OK);
Response
is a Controller
property, so you don't need to create any HttpResponseMessage
object. Response
是Controller
属性,因此不需要创建任何HttpResponseMessage
对象。
There are many ways to solve this, but I will show you mine. 有很多方法可以解决此问题,但我将向您展示。 Instead of HttpResponseMessage you can just do FileStreamResult.
除了HttpResponseMessage,您还可以执行FileStreamResult。 And You dont need to instantiate HttpResponseMessage, its already part of the controller method.
而且您不需要实例化HttpResponseMessage,它已经是控制器方法的一部分。 This is how I would start to try to fix your code.
这就是我开始尝试修复您的代码的方式。 Remember to use FileStreamResult instead.
记住要改用FileStreamResult。
public FileStreamResult DownloadExcel(???analystReport????)
{
MemoryStream memStream = ReportExporter.ExportReport(analystReport);
return new FileStreamResult(memStream , "application/vnd.ms-excel", saveAsFileName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.