Get current owin context in self host mode

前端 未结 2 1950
情话喂你
情话喂你 2021-02-04 09:46

I need to run my application which provides some ASP.NET Web API services on both IIS and .NET CLR self host modes. I developed my ASP.NET Web API services based on OWIN and it

相关标签:
2条回答
  • 2021-02-04 10:30

    You can use Request.GetOwinContext() for both web-hosting and self-hosting. GetOwinContext is an extension method for HttpRequestMessage and is defined in the System.Web.Http.Owin.dll assembly.

    UPDATE

    I have answered your original question, which is how to get OWIN context in both web-hosting and self-hosting. Now, through your additional question in the comment, you have significantly broadened the scope of your question. There is a fundamental problem though. IOwinContext is not a OWIN thing, it is a Katana thing. You cannot expect any framework hosted on OWIN to provide a context in the form of IOwinContext. ASP.NET Web API does but not every framework is supposed to. IOwinContext is an abstraction over OWIN environment dictionary and this dictionary will be available to any OWIN middleware. However, by working on top of a framework, you no longer can access the OWIN environment directly but only through how that specific framework has decided to expose the context.

    For Nancy, you have to use NancyContext to get to the Items dictionary and look for the value corresponding to the key "OWIN_REQUEST_ENVIRONMENT". For SignalR, Environment property of IRequest gives you access to OWIN environment. Once you have the OWIN environment, you can create a new OwinContext using the environment.

    0 讨论(0)
  • 2021-02-04 10:38

    First, I've to correct my question.

    HttpContext.Current is available in applications which are based on ASP.NET and integrated IIS pipeline.But We can't use this class without asp.net anywhere, even on IIS integrated pipeline.

    Answer:

    1- Anywhere you need IOwinContext, you've to get it, using dependency injection, for example by constructor injection.

    2- Configure everything to work based on Owin, SignalR is Owin based only, but use Web Api & owin together, and use nancy for server side views if any. Instead of writting IIS or ASP.NET handlers and modules, develop owin middlewares.

    3- Using Autofac.Owin & AutoFac.WebApi & AutoFac.WebApi.Owin & Autofac.SignalR, you can setup dependency injection working across all owin middlewares you've in your application.

    4- Autofac will instantiate web api controllers, signalr hubs and owin middlewares, and it will pass IOwinContext instance to classes you want using constructor injection.

    My tests are ok on Owin IIS/Helios (without asp.net) , Owin SelfHost and even Owin Test Server.

    This approach is similar to asp.net vNext. You can easily migrate your app to asp.net vNext, when it is production ready.

    0 讨论(0)
提交回复
热议问题