How do I retrieve the HttpContext properties when it returns null?

流过昼夜 提交于 2019-11-29 00:46:18

问题


I am doing some asynchronous work on a separate thread using:

ThreadPool.QueueUserWorkItem()

and in this separate thread, I need to call HttpContext.Current so that I can access:

HttpContext.Current.Cache  
HttpContext.Current.Server  
HttpContext.Current.Request  

However, HttpContext.Current is null when I create this separate thread.

Question

How do I create a new thread so that HttpContext.Current is not null? Or is there another way I can access the Cache, Server, and Request objects?


回答1:


I'd try not to hold a reference to an object that depends on the ASP.NET stack like the HttpContext. If you need to do some work in a different thread, it's because you don't want to wait in the ASP.NET one till your task is finished. And maybe the Request/Context/Session is terminated while your thread is not.

You should pass an object with the data needed for your thread.




回答2:


You can access the ASP.NET cache with HttpRuntime.Cache even when you don't have a HttpContext, but unfortunately you cannot access Server or Request.

If you think about it, this make sense - you are not serving any page so you don't have a request.




回答3:


1- Add bottom code in <system.serviceModel> in Web.config file:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> 

2- Add bottom code after NameSpace in web service file:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

3- Rebuild web part project. Done!

reference




回答4:


For HttpContext.Server services you can use HttpServerUtility class. For the Cache you can use HttpRuntime.Cache, as it has been said above. For the request object you can pass the data from the Request to the thread when it is created. Things like Request.QueryString or Request.Form... or whatever.




回答5:


There is a thread pool implementation here that provides propagation of the calling thread's HTTP context. I haven't used it yet but I plan to.




回答6:


If the separate thread is trying to access those objects, then yes they will be null. Those objects are scoped at the thread level. If you want to use them in a new thread you will have to pass them into the method/class where you need them.

Typically ASP.Net doesn't allow you to spawn new threads... Here is a post on the subject.

Here is a nice write up on threading in ASP.NET from MSDN.



来源:https://stackoverflow.com/questions/529286/how-do-i-retrieve-the-httpcontext-properties-when-it-returns-null

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