![](/img/trans.png)
[英]How do I remove the charset from Content-Type in a ASP.NET Core MVC response?
[英]Setting the Content-Type of an empty response in ASP.NET MVC
為了支持現場的遺留應用程序,我需要我的ASP.NET MVC應用程序返回一個也有Content-Type
的空響應。 當我發回null響應時,IIS,ASP.NET或ASP.NET MVC之一正在刪除我的Content-Type
。 有沒有辦法解決?
(雖然不需要設置Content-Type
的空響應顯然是理想的解決方案,但客戶已經在那里,其中許多都無法升級。)
編輯 :由於存在代碼請求:我正在將新Web應用程序的請求代理到舊客戶端所依賴的請求。 為此,我有一個ActionResult
的子類,名為LegacyResult
,您只需返回那些需要由舊軟件處理的方法。 這是其代碼的相關部分:
public override void ExecuteResult(ControllerContext context)
{
using (var legacyResponse = GetLegacyResponse(context))
{
var clientResponse = context.HttpContext.Response;
clientResponse.Buffer = false;
clientResponse.ContentType = legacyResponse.ContentType; /* Yes, I checked that legacyResponse.ContentType is never string.IsNullOrEmpty */
if (legacyResponse.ContentLength >= 0) clientResponse.AddHeader("Content-Length", legacyResponse.ContentLength.ToString());
var legacyInput = legacyResponse.GetResponseStream();
using (var clientOutput = clientResponse.OutputStream)
{
var rgb = new byte[32768];
int cb;
while ((cb = legacyInput.Read(rgb, 0, rgb.Length)) > 0)
{
clientOutput.Write(rgb, 0, cb);
}
clientOutput.Flush();
}
}
}
如果legacyInput
有數據,則適當地設置Content-Type
。 否則,事實並非如此。 我實際上可以克服舊的后端為完全相同的請求發送空的v。非空響應,並觀察Fiddler的差異。
編輯2 :使用Reflector進行調查顯示,如果在調用HttpResponse.Flush
時尚未寫入標題,則Flush
自行寫出標題。 問題是它只寫出一小部分標題。 其中一個缺少的是Content-Type
。 所以看來,如果我可以強制標題輸出到流,我可以避免這個問題。
你必須欺騙響應寫入標題,錯誤地告訴它有內容,然后抑制它 :
/// [inside the writing block]
var didWrite = false;
while ((cb = legacyInput.Read(rgb, 0, rgb.Length)) > 0)
{
didWrite = true;
clientOutput.Write(rgb, 0, cb);
}
if (!didWrite)
{
// The stream needs a non-zero content length to write the correct headers, but...
clientResponse.AddHeader("Content-Length", "1");
// ...this actually writes a "Content-Length: 0" header with the other headers.
clientResponse.SuppressContent = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.