Asp.net Web API返回文件,其中包含有关该文件的元数据

时间:2013-08-22 06:21:45

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

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

1 个答案:

答案 0 :(得分:2)

对于文件名,您最好使用专门为此目的设计的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;
}