【问题标题】:Can't set Content-Type header on HttpResponseMessage headers?无法在 HttpResponseMessage 标头上设置 Content-Type 标头?
【发布时间】:2012-11-02 21:33:09
【问题描述】:

我正在使用 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 使用浏览器放置到该位置时,它给了我这个异常:

错误的标题名称。确保请求标头与 HttpRequestMessage,带有 HttpResponseMessage 的响应标头,以及 带有 HttpContent 对象的内容标头。

但是Content-Type 不是一个完全有效的响应标头吗?为什么我会收到此异常?

【问题讨论】:

    标签: c# asp.net rest asp.net-web-api


    【解决方案1】:

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

    【讨论】:

    • 如果响应没有内容怎么办(所以.Content 为空)?即使没有内容,我也想设置 Content-Type 标头,否则 Firefox 会抱怨“找不到元素”错误。
    • 您也可以尝试设置response.StatusCode = HttpStatusCode.NoContent,而不是添加 Content-Type 标头字段。
    • 酷,假人response.Content = new StringContent(""); 工作了。不过,我仍然想知道为什么response.Headers 甚至存在。
    • 对于与Content无关的标头。
    • 这太荒谬了。我很高兴 WebApi 完成了。 MVC 万岁。
    【解决方案2】:

    ASP Web API 中缺少一些东西:EmptyContent 类型。它将允许发送空正文,同时仍允许所有特定于内容的标头。

    将以下类放在代码中的某处:

    public class EmptyContent : HttpContent
    {
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            return Task.CompletedTask;
        }
        protected override bool TryComputeLength(out long length)
        {
            length = 0L;
            return true;
        }
    }
    

    然后根据需要使用它。您现在有一个内容对象用于额外的标题。

    response.Content = new EmptyContent();
    response.Content.Headers.LastModified = file.DateUpdatedUtc;
    

    为什么使用EmptyContent 而不是new StringContent(string.Empty)

    • StringContent 是一个执行大量代码的重类(因为它继承了ByteArrayContent
      • 让我们节省几纳秒
    • StringContent 将添加一个额外的无用/有问题的标题:Content-Type: plain/text; charset=...
      • 所以让我们节省一些网络字节

    【讨论】:

      猜你喜欢
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 2013-07-22
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多