【问题标题】:Asp.net Web API return File with metadata about the fileAsp.net Web API 返回带有文件元数据的文件
【发布时间】:2013-08-22 22:41:18
【问题描述】:

我有一个下载文件的 web api 方法:

public HttpResponseMessage DownloadDocument()
{
    XDocument xDoc = GetXMLDocument();
    MemoryStream ms = new MemoryStream();
    xDoc.Save(ms);
    ms.Position = 0;

    var response = new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.OK,
        Content = new StreamContent(ms),
    };

    // Sending metadata
    // Is this the right way of sending metadata about the downloaded document?
    response.Content.Headers.Add("DocumentName", "statistics.xml");
    response.Content.Headers.Add("Publisher", "Bill John");

    return response;
}

这是发送有关我返回的 StreamContent 的元数据的正确方法吗?还是我应该返回不同类型的内容?

【问题讨论】:

    标签: c# asp.net-web-api


    【解决方案1】:

    对于文件名,您最好使用专门为此目的设计的Content-Disposition 响应标头。就 Publisher 而言,您确实可以使用自定义 HTTP 标头(就像您所做的那样),或者直接将其作为某种元数据标记包含在有效负载中。例如:

    public HttpResponseMessage Get()
    {
        XDocument xDoc = GetXMLDocument();
    
        var response = this.Request.CreateResponse(
            HttpStatusCode.OK, 
            xDoc.ToString(), 
            this.Configuration.Formatters.XmlFormatter
        );
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "statistics.xml"
        };
        response.Headers.Add("Publisher", "Bill John");
        return response;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 2016-04-23
      • 2013-03-21
      • 2016-04-23
      • 2015-07-09
      • 1970-01-01
      • 2016-12-17
      • 2020-04-16
      • 1970-01-01
      相关资源
      最近更新 更多