无法在HttpResponseMessage标头上设置Content-Type标头?

Jez*_*Jez 70 c# asp.net rest asp.net-web-api

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

当我通过AJAX将浏览器推送到该位置时,它给了我这个例外:

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

Content-Type对于回复来说,这不是一个完全有效的标题吗?为什么我得到这个例外?

dtb*_*dtb 110

看看HttpContentHeaders.ContentType属性:

response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
Run Code Online (Sandbox Code Playgroud)
if (response.Content == null)
{
    response.Content = new StringContent("");
    // The media type for the StringContent created defaults to text/plain.
}
Run Code Online (Sandbox Code Playgroud)

  • 这太荒谬了.我很高兴WebApi完成了.MVC万岁. (5认同)