HttpSelfHostServer and HttpContext.Current

荒凉一梦 提交于 2019-11-26 13:18:38

问题


I'm working on a self-hosted ASP.NET web api-application. Everything works fine, but now I'm struggling with HttpContext:

I need to save session-informations from the client. But HttpContext.Current is always null. So it's obvious that my HttpSelfHostServer don't work with the static HttpContext-Class.

The thing I don't understand is: why..? And I can't figure out a way to tell neither HtttpSelfHostServer nor HttpSelfHostConfiguration to work with HttpContext.

Here's what I'm doing:

  1. Creating a HttpSelfHostConfiguration

    • 1.1 Adding Service-Resolvers & Routes
    • 1.2 Adding custom UserNamePassword-Validator
  2. create new Instance of HttpSelfHostServer with the config

    • 2.1 server.OpenAsync().Wait()

Any help how I can tell my server to work with HttpContext.Current is greatly appreciated! Cheers!


回答1:


You won't be able to use HttpContext in a self-hosted environment. HttpContext is set by the ASP.Net pipeline, which you won't have if you don't run under IIS/ASP.Net.

The HttpContext is only available in the Web-Hosting mode, in which the HttpControllerHandler creates the request.

FYI- I invite you to read the following great articles from Pedro Felix to better understand the different hosting models:

  • HTTP processing architecture overview
  • Web-hosting
  • Self-hosting



回答2:


To get around this problem (I find I am using a lot of components these days that need to work equally well in Web API and MVC), you can try this old shim I wrote to give you back an HttpContext-like interface that works in both flavours. It's on NuGet also, here's the source: Link on github (or Link on Nuget)



来源:https://stackoverflow.com/questions/11347807/httpselfhostserver-and-httpcontext-current

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!