如何将Content-Length,Content-Type和Last-Modified添加到HTTP响应消息头 [英] How to add the Content-Length,Content-Type and Last-Modified to the HTTP Response Message Header

查看:138
本文介绍了如何将Content-Length,Content-Type和Last-Modified添加到HTTP响应消息头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





如何使用.net将内容长度,内容类型和最后修改添加到HttpResponseMessage标题。



我需要在添加这些字段后手动将所有这些值附加到响应中,我需要从服务器返回响应。

我试图添加这些以下方式的字段

Hi,

How to add the Content-Length,Content-Type and Last-Modified to the HttpResponseMessage Header using .net.

I need to append the all these values manually to the response after adding these fields i need to return the response from the server.
I have tried to adding these fields in fallowing way

httpResponse.Content.Headers.Add("Content-Length", item.Size.ToString());
   httpResponse.Content.Headers.Add("Content-Type", item.ContentType);







但它抛出异常为对象引用未设置为对象的实例 。



如果我这样添加




But it throwing the exception as "Object reference not set to an instance of an object".

If i am adding like this

httpResponse.Headers.Add("Content-Length", item.Size.ToString());
                  httpResponse.Headers.Add("Content-Type", item.ContentType);





我收到了错误的错误

未使用的标题名称。请确保请求标头与HttpRequestMessage一起使用,带有HttpResponseMessage的响应头和带有HttpContent对象的内容头。



请任何人帮我将这些字段添加到HttpResponsesMessage中。



谢谢

purna



I am getting the fallowing error
"Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."

Please any one help me to add these fields to the HttpResponsesMessage .

thanks
purna

推荐答案

内容类型应该是使用现有属性设置,如下例所示:

The "content type" should be set by using the existing property like in the next example:
httpResponse.ContentType = "application/vnd.ms-excel";





其他标题如添加文件下载应该与您的示例类似:



Other header like adding a file to download should be like in your example:

httpResponse.AddHeader("content-disposition", "attachment; filename=" + this.FileDownloadName);





你的对象httpResponse应该在后面的ASPX代码中使用,如下一个例子所示:



And your object httpResponse should be used from your ASPX code behind, like in the next example:

HttpResponse httpResponse = HttpContext.Current.Response;


我找到了我们可以添加的解决方案



I have find the solution we can add like this

httpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue(item.ContentType);
                  httpResponse.Content.Headers.ContentLength = item.Size;
                  var info = TimeZoneInfo.FindSystemTimeZoneById("UTC");
                  httpResponse.Content.Headers.LastModified = TimeZoneInfo.ConvertTime(item.LastModifiedDate, info);


这篇关于如何将Content-Length,Content-Type和Last-Modified添加到HTTP响应消息头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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