How to add the Content-Length,Content-Type and Last-Modified to the HTTP Response Message Header

旧巷老猫 提交于 2020-02-02 10:18:41

问题


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

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 .


回答1:


You basically need to initialise Content first. For example:

var content = "this is some content";
var response = new HttpResponseMessage
{
    Content = new StringContent(content)
};
response.Content.Headers.Add(@"Content-Length", content.Length.ToString());


来源:https://stackoverflow.com/questions/22499258/how-to-add-the-content-length-content-type-and-last-modified-to-the-http-respons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!