gpt4 book ai didi

c# - 如何从 web api Controller 返回文件?

转载 作者:太空狗 更新时间:2023-10-29 21:12:33 24 4
gpt4 key购买 nike

我正在使用 MVC 5 web Api Controller ,我想返回一个文件:

[Route("")]
public HttpResponseMessage GetFile()
{
var statusCode = HttpStatusCode.OK;
FileStream file = XLGeneration.XLGeneration.getXLFileExigence();

return Request.CreateResponse(statusCode, file);
}

这是行不通的。

postman 的异常(exception)情况是:

"ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."

最佳答案

我正在发布对我有用的替代方案,以防其他人遇到麻烦。

[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;
}

关于c# - 如何从 web api Controller 返回文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30125702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com