Asp.net Web API返回文件以及有关该文件的元数据 [英] Asp.net Web API return File with metadata about the file

查看:47
本文介绍了Asp.net Web API返回文件以及有关该文件的元数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web api方法可以下载文件:

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

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

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

推荐答案

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

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

这篇关于Asp.net Web API返回文件以及有关该文件的元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆