簡體   English   中英

如何將Content-Length,Content-Type和Last-Modified添加到HTTP響應消息頭中

[英]How to add the Content-Length,Content-Type and Last-Modified to the HTTP Response Message Header

如何使用.net將Content-Length,Content-Type和Last-Modified添加到HttpResponseMessage標頭。

添加這些字段后,我需要將所有這些值手動附加到響應中,我需要從服務器返回響應。 我試圖以休閑的方式添加這些字段

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中。

基本上,您首先需要初始化內容。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM