测试从 ASP.NET MVC 应用程序返回的 HTTP headers

Testing for HTTP headers being returned from an ASP.NET MVC Application

出于安全原因,我添加和删除了一些 headers,在 MVC 应用程序中使用了两种经典策略:

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
    HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
    HttpContext.Current.Response.Headers.Remove("Server");
    HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
}

并通过 Web.Config:

<customHeaders>
    <remove name="X-Powered-By" />
    <add name="X-Frame-Options" value="DENY" />
</customHeaders>

现在我正在使用 NUnitRhinoMocks 配对进行测试,FWIW。

考虑到模拟 HttpContext 的困难,什么是确保自定义 headers 在任何我的观看次数 return?

验证此行为的正确方法是通过组件测试。原因很简单;您正在尝试确保安全问题,在 UT 中没有任何东西可以确保您的组件将使用此行为。我可以为您提供几个选项(代码编织工具、添加 public 方法等)来将其作为 UT 进行测试,但是,IMO 这是集成测试的经典案例。

要组件测试此行为,请执行以下步骤:

建立一个自托管服务器(Self-Host ASP.NET or OWIN to Self-Host ASP.NET)

然后调用方法并断言答案不包含 headers:

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();  

Assert.IsFalse(myHttpWebResponse.Headers.ContainsKey("X-Frame-Options");
Assert.IsFalse(myHttpWebResponse.Headers.ContainsKey("Server");
Assert.IsFalse(myHttpWebResponse.Headers.ContainsKey("X-AspNetMvc-Version");
//todo: add logic which read the following parameters from the configuration
Assert.IsFalse(myHttpWebResponse.Headers.ContainsKey("X-AspNet-Version");
Assert.AreEquals("DENY", myHttpWebResponse.Headers["X-Frame-Options"]);