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

博客讨论了在ASP.NET WebAPI中如何为下载文件设置默认名称,避免用户每次保存时手动修改。通过在HttpResponseMessage的Content-Disposition头中指定文件名,可以实现这一功能。示例代码展示了如何在Action方法中添加相应头来设定文件默认名。
摘要由CSDN通过智能技术生成

咨询区

  • 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,学习了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值