出于安全原因,我在 MVC 应用程序中使用两种经典策略添加和删除了许多 header :
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>
目前我正在使用 NUnit 搭配 RhinoMocks 进行测试,FWIW。
考虑到模拟 HttpContext
的困难,什么是确保自定义 header 存在或不存在于我返回的任何 View 的 http 响应中的好方法?
最佳答案
验证此行为的正确方法是通过组件测试。原因很简单;您正在尝试确保安全问题,在 UT 中没有任何东西可以确保您的组件将使用此行为。我可以为您提供几个选项(代码编织工具、添加公共(public)方法等)来将其作为 UT 进行测试,但是,IMO 这是集成测试的经典案例。
要组件测试此行为,请执行以下步骤:
建立一个自托管服务器(Self-Host ASP.NET 或 OWIN to Self-Host ASP.NET)
然后调用一个方法并断言答案不包含标题:
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"]);
关于asp.net-mvc - 测试从 ASP.NET MVC 应用程序返回的 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485142/