Asp.net-Web-Api
從響應中刪除標頭
我需要隱藏由 ASP.NET 和 IIS 生成並在 ASP.NET WebAPI 服務的響應中返回的某些標頭。我需要隱藏的標題是:
- 伺服器
- X-AspNet-版本
- X-AspNetMvc-版本
- X-Powered-By
該服務之前託管在 WCF 中,並且通過訂閱 PreSendRequestHeaders 並操作 HttpContext.Current.Response.Headers 在 HttpModule 中完成偽裝。使用 ASP.NET WebAPI,一切現在都是基於任務的,因此 HttpContext.Current 為空。我試圖插入一個消息處理程序並操作返回的 HttpResponseMessage,但該階段上不存在標頭。X-Powered-By 可以在 IIS 設置中刪除,但是建議的刪除其餘部分的方法是什麼?
問題是每個都在不同的點添加:
Server: 由 IIS 添加。儘管您似乎已經使用 HttpModule 將其刪除,但不確定是否可以將其關閉。X-AspNet-Version:由 System.Web.dll 在HttpResponse課堂上 Flush 時添加X-AspNetMvc-Version:MvcHandler在 System.Web.dll 中添加。它可以被覆蓋,所以這個應該沒問題。X-Powered-By由 IIS 但可以按您所說的那樣關閉。我認為你最好的選擇仍然是使用 HttpModules。
為了那些通過 google/bing 搜尋登陸這裡的人的利益:: 以下是步驟摘要:
**第 1 步:**創建一個派生自 IHttpModule 的類(以及 IDisposable 以在我們完成後清理):
public class MyCustomModule : IHttpModule, IDisposable { private HttpApplication _httpApplication private static readonly List<string> HeadersToCloak = new List<string> { "Server", "X-AspNet-Version", "X-AspNetMvc-Version", "X-Powered-By" }; .. }**第 2 步:**在 IHttpModule.Init 方法中獲取對內部上下文的引用,並將事件處理程序分配給 PreSendRequestHeaders 事件:
public void Init(HttpApplication context) { _httpApplication = context; context.PreSendRequestHeaders += OnPreSendRequestHeaders; }**第 3 步:**現在可以像這樣刪除標題:
private void OnPreSendRequestHeaders(object sender, EventArgs e) { if (null == _httpApplication) { return; } if (_httpApplication.Context != null) { var response = _httpApplication.Response; HeadersToCloak.ForEach(header => response.Headers.Remove(header)); } }**第 4 步:**現在在 system.webserver 下的根 web.config 中註冊此模組(如果執行 IIS 7.0 集成模式,請在此處查看更多詳細資訊):
<configuration> <system.webServer> <modules> <add name="MyCustomModule" type="<namespace>.MyCustomModule "/> </modules> </system.webServer> </configuration>希望這可以幫助!