Can't set Content-Type header on HttpResponseMessage headers?

Jez picture Jez · Nov 14, 2012 · Viewed 72.2k times · Source

I'm using the ASP.NET WebApi to create a RESTful API. I'm creating a PUT method within one of my controllers, and the code looks like this:

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 PUT to that location with the browser via AJAX, it gives me this Exception:

Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

But isn't Content-Type a perfectly valid header for a response? Why am I getting this exception?

Answer

dtb picture dtb · Nov 14, 2012

Have 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.
}