Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a content Header Type for adding HttpResponseHeader?

The only method I see in HttpResponseHeaders is Add which takes string type for header type. I just wonder did .NET provided a list of HttpResponseHeader type contants in string?

So I can do:

HttpResponseMessage response = Request.CreateResponse.........;
response.Headers.Add(xxxxx.ContentRange, "something");

I can see there is a list of Enum in HttpResponseHeader, but it doesn't provide string value conrespondingly...

i.e HttpResponseHeader.ContentRange, but the correct header string should be Content-Range

Correct me if I am wrong...

like image 897
King Chan Avatar asked Mar 11 '13 16:03

King Chan


2 Answers

There are three strongly-typed HTTP header classes in the System.Net.Http.Headers namespace:

  • HttpContentHeaders
  • HttpRequestHeaders
  • HttpResponseHeaders

HttpContentHeaders (which is accessible via the Headers property of any of the System.Net.Http.HttpContent types) has pre-defined properties for Content-Type, Content-Length, Content-Encoding etc... (which seem to be the headers you were after).

You can set them like this:

var content = new StringContent("foo");
content.Headers.Expires = DateTime.Now.AddHours(4);
content.Headers.ContentType.MediaType = "text/plain";

...and the header names will be set correctly.

like image 174
mthierba Avatar answered Oct 11 '22 21:10

mthierba


Maybe you can try something like this.

var whc = new System.Net.WebHeaderCollection();
whc.Add(System.Net.HttpResponseHeader.ContentRange, "myvalue");
Response.Headers.Add(whc);

In a webapi context, the last line could be :

HttpContext.Current.Response.Headers.Add(whc);

anyway, @ServiceGuy's answer is the way to go in a webapi/mvc context

Hope this will help

like image 21
jbl Avatar answered Oct 11 '22 21:10

jbl