Asp.net Web API返回文件以及有关该文件的元数据

编程入门 行业动态 更新时间:2024-10-18 12:25:48
本文介绍了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返回文件以及有关该文件的元数据

本文发布于:2023-11-13 15:10:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:该文件   文件   数据   net   Asp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!