[英]Difference between HttpControllerContext.Request and HttpContext.Current.Request
Im just trying to Unit-Test my custom ApiController
. 我只是想对我的自定义ApiController
进行单元测试。 In my custom controller i override the Initialize
method to evaluate the authorization-header. 在我的自定义控制器中,我重写了Initialize
方法来评估授权标头。
So my problem is, that i there are 2 request-headers available. 所以我的问题是,我有2个请求标头可用。
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
// Headers 1
var headersOne = controllerContext.Request.Headers;
// Headers 2
var headersTwo = HttpContext.Current.Request.Headers;
}
But this it not the problem itself. 但这不是问题本身。 The problem is, that the headers don't match. 问题是,标题不匹配。 So for the productive operating: Where do i have to look for the authorization-header. 因此,对于生产性操作:我必须在哪里查找授权标题。 And where do i have to apply my authorization-header for my test-scenario. 在测试场景中,我必须在哪里应用我的授权标题。
At the moment i apply the authorization-header to the controllerContext
: 目前,我将授权标头应用于controllerContext
:
var fakeControllerContext = new HttpControllerContext
{
Request = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost/api/test"),
Headers =
{
{ "Authorization", "Fake Authorization-Header"}
}
}
};
But as i already said. 但是正如我已经说过的。 The header is later not available in HttpContext.Current.Request.Headers
. 标头后来在HttpContext.Current.Request.Headers
不可用。 Can you please help me out? 你能帮我吗? Unfortunately i don't exactly understand which context fulfills what purpose. 不幸的是,我不完全了解哪个上下文可以实现什么目的。
What i found out now is that HttpContext.Current
is an old implementation which should not be used anymore. 我现在发现的是HttpContext.Current
是一个旧的实现,不应再使用。 Because you can not take control over it's content to unit-test it. 因为您无法控制它的内容以进行单元测试。
HttpControllerContext
is just the newer implementation. HttpControllerContext
只是更新的实现。 And it's content is also exchangable. 而且它的内容也是可以互换的。 The submitted controllerContext to the method initialize is available in ControllerContext
-Property. 在ControllerContext
-Property中提供了向方法initialize提交的controllerContext。 So you should use this. 因此,您应该使用它。
Found this here in first answer: Testing a Web API method that uses HttpContext.Current.Request.Files? 在第一个答案中找到此内容: 测试使用HttpContext.Current.Request.Files的Web API方法? Thanks to: Martin Liversage 感谢:马丁·利弗塞奇
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.