GVKun编程网logo

如何在 ASP.NET WebAPI 中返回文件 (FileContentResult)(webapi返回文件流)

24

如果您对如何在ASP.NETWebAPI中返回文件(FileContentResult)和webapi返回文件流感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解如何在ASP.NETWebAPI中

如果您对如何在 ASP.NET WebAPI 中返回文件 (FileContentResult)webapi返回文件流感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解如何在 ASP.NET WebAPI 中返回文件 (FileContentResult)的各种细节,并对webapi返回文件流进行深入的分析,此外还有关于$results = json_decode($contents, true);返回null如何解决、ASP.Net Core Web API 如何返回 File。、ASP.NET MVC Controller FileContent ActionResult通过AJAX调用、ASP.NET MVC的OnResultExecuted方法中的ActionResult的filterContext的实用技巧。

本文目录一览:

如何在 ASP.NET WebAPI 中返回文件 (FileContentResult)(webapi返回文件流)

如何在 ASP.NET WebAPI 中返回文件 (FileContentResult)(webapi返回文件流)

在常规的 MVC 控制器中,我们可以输出带有FileContentResult.

public FileContentResult Test(TestViewModel vm){    var stream = new MemoryStream();    //... add content to the stream.    return File(stream.GetBuffer(), "application/pdf", "test.pdf");}

但是我们怎样才能把它变成一个ApiController

[HttpPost]public IHttpActionResult Test(TestViewModel vm){     //...     return Ok(pdfOutput);}

这是我尝试过的,但似乎不起作用。

[HttpGet]public IHttpActionResult Test(){    var stream = new MemoryStream();    //...    var content = new StreamContent(stream);    content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");    content.Headers.ContentLength = stream.GetBuffer().Length;    return Ok(content);            }

浏览器中显示的返回结果为:

{"Headers":[{"Key":"Content-Type","Value":["application/pdf"]},{"Key":"Content-Length","Value":["152844"]}]}

SO上有一个类似的帖子:Returning binary file from controller in ASP.NET Web API
。它谈论输出现有文件。但我无法让它与流一起工作。

有什么建议么?

答案1

小编典典

StreamContent而不是作为返回Content,我可以使它与ByteArrayContent.

[HttpGet]public HttpResponseMessage Generate(){    var stream = new MemoryStream();    // processing the stream.    var result = new HttpResponseMessage(HttpStatusCode.OK)    {        Content = new ByteArrayContent(stream.ToArray())    };    result.Content.Headers.ContentDisposition =        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")    {        FileName = "CertificationCard.pdf"    };    result.Content.Headers.ContentType =        new MediaTypeHeaderValue("application/octet-stream");    return result;}

$results = json_decode($contents, true);返回null如何解决

$results = json_decode($contents, true);返回null如何解决

$results = json_decode($contents, true);返回null如何解决,看了微信那边返回的是utf-8字符编码的json,但是json_decode()返回error_code:4, error_msg:syntax error;其实是一些看不见的字符,总不能每次把看不见的字符搂出来,一个个preg_replace()了,有没有通用的方法呢?网上搜了很多答案都解决不了。

回复内容:

$results = json_decode($contents, true);返回null如何解决,看了微信那边返回的是utf-8字符编码的json,但是json_decode()返回error_code:4, error_msg:syntax error;其实是一些看不见的字符,总不能每次把看不见的字符搂出来,一个个preg_replace()了,有没有通用的方法呢?网上搜了很多答案都解决不了。

你不把不更的信息贴出来,谁能帮的了你呢?我做过微信公众号和企业号,好像没有这样的问题呢。json_decode本来就是处理utf-8字符集的。

results = json_decode($contents, true);
把$content 打印到一个log文件里 对比下 试试把日志的内容直接json_decode

ASP.Net Core Web API 如何返回 File。

ASP.Net Core Web API 如何返回 File。

咨询区

  • Jan Kruse

我想在 ASP.Net Web API 中返回 File 文件,我目前的做法是将 Action 返回值设为 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;
}

当我在浏览器测试时,我发现Api将 HttpResponseMessage 作为 json格式返回,同时 Http Header 头为 application/json,请问我该如何正确配置成文件流返回。

回答区

  • H. Naeemaei

我觉得大概有两种做法:

  1. 返回 FileStreamResult

    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."
        Stream stream = await GetFileStreamById(id);

        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }

  1. 返回 FileContentResult

    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."
        byte[] fileBytes = await GetFileBytesById(id);

        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }

  • Nkosi

这是因为你的代码将 HttpResponseMessage 视为一个 Model,如果你的代码是 Asp.NET Core 的话,其实你可以混入一些其他特性,比如将你的 Action 返回值设置为一个派生自 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
    }    
}

点评区

记得我在 webapi 中实现类似功能时,我用的就是后面这位大佬提供的方式, ActionResult + File 的方式,简单粗暴。


本文分享自微信公众号 - dotNET跨平台(opendotnet)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

ASP.NET MVC Controller FileContent ActionResult通过AJAX调用

ASP.NET MVC Controller FileContent ActionResult通过AJAX调用

设置:

控制器包含一个方法public ActionResult SaveFile(),它返回一个FileContentResult.

什么工作:

该视图包含一个表单,它提交到此操作.结果是这个对话框:

什么不行:

该视图包含一些javascript来执行AJAX调用到表单将发布的相同的控制器操作.而不是触发上述对话框,甚至是AJAX成功函数,响应触发AJAX错误函数,XMLHttpRequest.responseText包含文件响应.

我需要做什么:

使用AJAX对文件进行请求,结果与提交表单时的结果相同.如何使AJAX请求提供提交表单的对话框?

解决方法

这是一个快速的例子.这是LukLed正在调用SaveFile的概念,但是不要通过ajax返回文件内容,而是重定向到下载.

这是查看代码:

<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function() {
        // hide form code here

        // upload to server
        $('#btnUpload').click(function() {
            $.ajax({
                type: 'POST',dataType: 'json',url: '<%= Url.Action("SaveFile","Home") %>',success: function(fileId) {
                    window.location = '<%= Url.Action("DownloadFile","Home") %>?fileId=' + fileId;
                },error: function() {
                    alert('An error occurred uploading data.');
                }
            });
        });
    });
</script>

<% using (Html.BeginForm()) { %>

    <div>Field 1: <%= Html.TextBox("field1") %></div>

    <div>Field 2: <%= Html.TextBox("field2") %></div>

    <div>Field 3: <%= Html.TextBox("field3") %></div>

    <button id="btnUpload" type="button">Upload</button>

<% } %>

这是控制器代码:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult SaveFile(string field1,string field2,string field3)
    {
        // save the data to the database or where ever
        int savedFileId = 1;

        // return the saved file id to the browser
        return Json(savedFileId);
    }

    public FileContentResult DownloadFile(int fileId)
    {
        // load file content from db or file system
        string fileContents = "field1,field2,field3";

        // convert to byte array
        // use a different encoding if needed
        var encoding = new System.Text.ASCIIEncoding();
        byte[] returnContent = encoding.GetBytes(fileContents);

        return File(returnContent,"application/CSV","test.csv");
    }

    public ActionResult About()
    {
        return View();
    }
}

ASP.NET MVC的OnResultExecuted方法中的ActionResult的filterContext

ASP.NET MVC的OnResultExecuted方法中的ActionResult的filterContext

我需要仅从控制器操作中返回具有返回类型ActionResult的所有操作中的方法.
我从以下获取控制器名称和操作名称..
string originController = filterContext.RouteData.Values["controller"].ToString();
string originAction = filterContext.RouteData.Values["action"].ToString();

但是我怎样才能过滤只有返回类型ActionResult的方法?

解决方法

尝试使用这种代码来访问控制器,操作以及
string originController = filterContext.RouteData.Values["controller"].ToString();
  string originAction = filterContext.RouteData.Values["action"].ToString();
  string originArea = String.Empty;
   if (filterContext.RouteData.DataTokens.ContainsKey("area"))
       originArea = filterContext.RouteData.DataTokens["area"].ToString();

关于如何在 ASP.NET WebAPI 中返回文件 (FileContentResult)webapi返回文件流的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于$results = json_decode($contents, true);返回null如何解决、ASP.Net Core Web API 如何返回 File。、ASP.NET MVC Controller FileContent ActionResult通过AJAX调用、ASP.NET MVC的OnResultExecuted方法中的ActionResult的filterContext等相关知识的信息别忘了在本站进行查找喔。

本文标签:

上一篇从 PKCS12 文件中提取公钥/私钥供以后在 SSH-PK-Authentication 中使用(pkcs8和pkcs1公钥转换)

下一篇为什么在C#中“ int []是uint [] == true”(c语言为什么int main)