0

我有一个下载文件的 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 元数据的正确方法吗?还是我应该返回不同类型的内容?

4

1 回答 1

2

对于文件名,您最好使用Content-Disposition专门为此目的设计的响应标头。就发布者而言,您确实可以使用自定义 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;
}
于 2013-08-22T14:41:18.243 回答