不能在HttpResponseMessage报头上设置内容类型报头?

时间:2022-04-03 12:52:39

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:

我使用ASP。NET WebApi创建一个RESTful API。我正在我的一个控制器中创建一个PUT方法,代码是这样的:

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:

当我通过AJAX将浏览器放置到那个位置时,它给了我一个例外:

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

滥用标题名称。确保与HttpRequestMessage一起使用请求头,与HttpResponseMessage一起使用响应头,与HttpContent对象一起使用内容头。

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

但是,内容类型不是响应的一个完全有效的头吗?为什么我有这个例外?

1 个解决方案

#1


94  

Have a look at the HttpContentHeaders.ContentType Property:

看看httpcontentheader。ContentType属性:

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

#1


94  

Have a look at the HttpContentHeaders.ContentType Property:

看看httpcontentheader。ContentType属性:

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