程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在ASP.Net Core Web API中返回文件大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在ASP.Net Core Web API中返回文件?

开发过程中遇到在ASP.Net Core Web API中返回文件的问题如何解决?下面主要结合日常开发的经验,给出你关于在ASP.Net Core Web API中返回文件的解决方法建议,希望对你解决在ASP.Net Core Web API中返回文件有所启发或帮助;

如果这是ASP.net-Core,则您正在混合使用Web API版本。让操作返回一个派生,IActionResult因为在您当前的代码中,该框架被httpResponsemessage视为模型。

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

解决方法

问题

我想在ASP.Net Web API控制器中返回文件,但是所有方法都将httpResponsemessageJSON 返回。

到目前为止的代码

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

大佬总结

以上是大佬教程为你收集整理的在ASP.Net Core Web API中返回文件全部内容,希望文章能够帮你解决在ASP.Net Core Web API中返回文件所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。