Can't set Content-Type header on HttpResponseM

2019-03-22 18:30发布

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?

1条回答
不美不萌又怎样
2楼-- · 2019-03-22 19:02

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.
}
查看更多
登录 后发表回答