Asp.net Web API return File with metadata about th

2019-08-28 02:53发布

I have a web api method that downloads a file:

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;
}

Is this the correct way of sending metadata about the StreamContent i return? or should i return a different type of Content?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-28 03:07

For the filename you'd better use the Content-Disposition response header which is specifically designed for this purpose. As far as the Publisher is concerned, you could indeed use a custom HTTP header (as you did) or simply include it as some sort of metadata tag directly inside the payload. For example:

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;
}
查看更多
登录 后发表回答