ChatGPT解决这个技术问题 Extra ChatGPT

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

我正在使用 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 不是一个完全有效的响应标头吗?为什么我会收到此异常?


d
dtb

查看 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 万岁。
S
SandRock

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=... 所以让我们节省一些网络字节

所以让我们节省一些网络字节


关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅