Andrew
Andrew

Reputation: 412

How to get HttpRequestBase from IOwinContext

I started using Owin self host for my API and now I'm trying to fix some tests, which started to fail, because Owin does not support HttpContext.Current

Now I'm stuck in getting HttpRequestBase from IOwinContext. Here's my old code, which I used before Owin:

public static HttpRequestBase GetRequestBase(this HttpRequestMessage request)
{
    return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request;
}

And here's my try based on this answer:

public static HttpRequestBase GetRequestBase(this HttpRequestMessage request)
{
    var context = request.GetOwinContext();

    HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName); // <---- Returns null

    return httpContext.Request;
}

The problem is that httpContext variable returns null and I don't know what's wrong.

Does anybody know how to get HttpRequestBase using Owin?

Upvotes: 3

Views: 3602

Answers (1)

vendettamit
vendettamit

Reputation: 14677

I guess you must be using System.web hosting for your webApi which is why your tests were running. Now since you have started using the OwinSelf hosting the HttpContext is no more in the picture. That's the reason you are getting null.

This is the reason we have extension methods to get OwinContext from HttpContext/Requests but there's no extension method to get the HttpContext from OwinContext.

Unfortunately you have to remove/change the above test for Self hosting.

Upvotes: 2

Related Questions