本文介绍了Asp 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返回文件以及有关该文件的元数据
发布评论