首页 文章

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

提问于
浏览
62

我正在使用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;
}

当我通过AJAX使用浏览器将该位置移至该位置时,它给出了我的例外情况:

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

但是 Content-Type 不是一个完全有效的回复 Headers 吗?为什么我得到这个例外?

1 回答

  • 101

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

相关问题