简体   繁体   English

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

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

I'm using the ASP.NET WebApi.我正在使用 ASP.NET WebApi。 I'm creating a PUT method within one of my controllers, and the code looks like this:我正在我的一个控制器中创建一个 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?但是Content-Type不是一个完全有效的响应标头吗? Why am I getting this exception?为什么我会收到此异常?

Have a look at the HttpContentHeaders.ContentType Property :看看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.
}

Something is missing in ASP Web API: the EmptyContent type. ASP Web API 中缺少一些东西: EmptyContent类型。 It will allow sending an empty body while still allowing all content-specific headers.它将允许发送空正文,同时仍允许所有特定于内容的标头。

Put the following class somewhere in your code :将以下类放在代码中的某个位置:

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

Then use it as you wish.然后根据需要使用它。 You now have a content object for your extra headers.您现在有一个用于额外标题的内容对象。

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

Why use EmptyContent instead of new StringContent(string.Empty) ?为什么使用EmptyContent而不是new StringContent(string.Empty)

  • StringContent is a heavy class that executes lots of codes (because it inherits ByteArrayContent ) StringContent是一个执行大量代码的重类(因为它继承了ByteArrayContent
    • so let's save a few nanoseconds所以让我们节省几纳秒
  • StringContent will add an extra useless/problematic header: Content-Type: plain/text; charset=... StringContent将添加一个额外的无用/有问题的标题: Content-Type: plain/text; charset=... Content-Type: plain/text; charset=...
    • so let's save a few network bytes所以让我们节省一些网络字节

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

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