简体   繁体   中英

Difference between HttpControllerContext.Request and HttpContext.Current.Request

Im just trying to Unit-Test my custom ApiController . In my custom controller i override the Initialize method to evaluate the authorization-header.

So my problem is, that i there are 2 request-headers available.

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 :

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 . 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. Because you can not take control over it's content to unit-test it.

HttpControllerContext is just the newer implementation. And it's content is also exchangable. The submitted controllerContext to the method initialize is available in ControllerContext -Property. So you should use this.

Found this here in first answer: Testing a Web API method that uses HttpContext.Current.Request.Files? Thanks to: Martin Liversage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM