Can't set the Content-Type header in the HttpResponseMessage headers?

I am using ASP.NET WebApi to create a RESTful API. I am creating a PUT method in one of my controllers, and the code is as follows:

public HttpResponseMessage Put(int idAssessment, int idCaseStudy, string value) { var response = Request.CreateResponse(); if (!response.Headers.Contains("Content-Type")) { response.Headers.Add("Content-Type", "text/plain"); } response.StatusCode = HttpStatusCode.OK; return response; } 

When I go to this place using a browser via AJAX, it gives me this exception:

Invalid header name. Ensure that request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

But is Content-Type legitimate response header? Why am I getting this exception?

+64
c # rest asp.net-web-api
Nov 14 '12 at 11:29
source share
2 answers

Take a look at the HttpContentHeaders.ContentType Property :

 response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); 



 if (response.Content == null) { response.Content = new StringContent(""); // The media type for the StringContent created defaults to text/plain. } 
+106
Nov 14 '12 at 11:39
source

There is something missing in the ASP Web API: type EmptyContent . This will allow you to send an empty body, while at the same time allowing all headers depending on the content.

Put the following class somewhere in your code:

 public class EmptyContent : HttpContent { protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { return Task.CompletedTask; } protected override bool TryComputeLength(out long length) { length = 0L; return true; } } 

Then use it however you want. You now have a content object for your additional headers.

 response.Content = new EmptyContent(); response.Content.Headers.LastModified = file.DateUpdatedUtc; 

Why use EmptyContent instead of new StringContent(string.Empty) ?

  • StringContent is a heavy class that executes many codes (because it inherits ByteArrayContent )
    • so let's save a few nanoseconds
  • StringContent will add an extra useless / problematic header: Content-Type: plain/text; charset=... Content-Type: plain/text; charset=... Content-Type: plain/text; charset=... Content-Type: plain/text; charset=...
    • so let's save some network bytes
0
Jul 12 '19 at 17:44
source



All Articles