【问题标题】:How to add the Content-Length,Content-Type and Last-Modified to the HTTP Response Message Header如何在 HTTP 响应消息头中添加 Content-Length、Content-Type 和 Last-Modified
【发布时间】:2014-04-25 07:23:44
【问题描述】:

如何使用 .net 将 Content-Length、Content-Type 和 Last-Modified 添加到 HttpResponseMessage Header。

添加这些字段后,我需要手动将所有这些值附加到响应中,我需要从服务器返回响应。 我试图以休闲的方式添加这些字段

httpResponse.Content.Headers.Add("Content-Length", item.Size.ToString());
httpResponse.Content.Headers.Add("Content-Type", item.ContentType);

但它抛出异常

“对象引用未设置为对象的实例”。

如果我这样添加

httpResponse.Headers.Add("Content-Length", item.Size.ToString());
httpResponse.Headers.Add("Content-Type", item.ContentType);

我得到了休闲错误

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

请任何人帮助我将这些字段添加到 HttpResponsesMessage 。

【问题讨论】:

标签: c# .net httpresponse


【解决方案1】:

你基本上需要先初始化内容。例如:

var content = "this is some content";
var response = new HttpResponseMessage
{
    Content = new StringContent(content)
};
response.Content.Headers.Add(@"Content-Length", content.Length.ToString());

【讨论】:

    猜你喜欢
    • 2011-02-03
    • 1970-01-01
    • 2018-04-09
    • 2016-01-30
    • 2015-04-17
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多