Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 648
Andrew Avatar asked Jan 30 '26 17:01

Andrew


1 Answers

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.

like image 186
vendettamit Avatar answered Feb 01 '26 05:02

vendettamit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!