我想在ASP.Net Web API控制器中返回文件,但是所有方法都将HttpResponseMessageJSON 返回。
HttpResponseMessage
public async Task<HttpResponseMessage> DownloadAsync(string id) { var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent({{__insert_stream_here__}}); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return response; }
当我在浏览器中调用此终结点时,Web API会将HttpResponseMessageHTTP内容标头设置为,以JSON形式返回application/json。
application/json
如果这是ASP.net-Core,则您正在混合使用Web API版本。让操作返回一个派生,IActionResult因为在您当前的代码中,该框架被HttpResponseMessage视为模型。
IActionResult
[Route("api/[controller]")] public class DownloadController : Controller { //GET api/download/12345abc [HttpGet("{id}"] public async Task<IActionResult> Download(string id) { Stream stream = await {{__get_stream_based_on_id_here__}} if(stream == null) return NotFound(); // returns a NotFoundResult with Status404NotFound response. return File(stream, "application/octet-stream"); // returns a FileStreamResult } }