繁体   English   中英

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

[英]Can't set Content-Type header on HttpResponseMessage headers?

我正在使用 ASP.NET WebApi。 我正在我的一个控制器中创建一个 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不是一个完全有效的响应标头吗? 为什么我会收到此异常?

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

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=... Content-Type: plain/text; charset=...
    • 所以让我们节省一些网络字节

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM