0

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.

Daniel
  • 486
  • 4
  • 19
  • Maybe here is the anwer: http://stackoverflow.com/questions/31189028/testing-a-web-api-method-that-uses-httpcontext-current-request-files – Daniel Jul 16 '15 at 09:46

1 Answers1

2

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

Community
  • 1
  • 1
Daniel
  • 486
  • 4
  • 19