您当前的位置: 首页 >  .net

寒冰屋

暂无认证

  • 3浏览

    0关注

    2286博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

如何在 ASP.NET Web API 中设置下载文件名 ?

寒冰屋 发布时间:2021-10-24 22:34:33 ,浏览量:3

咨询区
  • Tae-Sung Shin:

在我的 ApiController 类中,有一个下载文件的Action方法,代码如下:

public HttpResponseMessage Get(int id)
{
    try
    {
        string dir = HttpContext.Current.Server.MapPath("~"); //location of the template file
        Stream file = new MemoryStream();
        Stream result = _service.GetMyForm(id, dir, file);
        if (result == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        result.Position = 0;
        HttpResponseMessage response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.OK;
        response.Content = new StreamContent(result);
        return response;
    }
    catch (IOException)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
}

代码运行是没有任何问题的,有一点不爽的是每次下载的文件名都是一串id,导致用户每次在对话框中保存的时候都需要修改成语义化的名字,我的想法是能不能在 API 端直接设置成默认名字呢?

回答区
  • Darin Dimitrov:

这个很简单,在 HttpResponseMessage 的 header 中设置一下 Content-Disposition 即可,参考如下代码:

HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "foo.txt"
};

  • sorenhk:

只要确保你的文件名是一个正确编码的格式,而且你也不想用 WebApi 的 HttpResponseMessage 的话,推荐直接设置 Response, 参考如下代码:

Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition("attachment") { FileName = "foo.txt" }.ToString());

或者这样:

Response.Headers.Add("Content-Disposition", $"attachment; filename={myFileName}");

点评区

这种需求在 webapi 开发中还是蛮容易遇到的,不管什么途径最终都是设置 Content-Disposition,学习了。

关注
打赏
1665926880
查看更多评论
立即登录/注册

微信扫码登录

0.0497s