asp.net mvc - Principal.Identity.Name in Task ran from Controller Action -


in controller action i'm running

public actionresult myaction() {     task.factory.startnew( () =>     {         myservice.executemethod( someargs );     } ); } 

the service call other class methods call others, , somewhere down line, iprincipal injected constructor of class.

the iprincipal created doing httpcontext.current.user.

since code in task, runs on different thread, , action has returned httpcontext.current null.

if try doing thread.currentprincipal, exists, set other httpcontext.current.user was. also, if try accessing thread.currentprincipal.identity.name, objectdisposedexception thrown.

i'm using ninject ioc container. iprincipal binding looks this

bind<iprincipal>().tomethod( x => httpcontext.current.user ); 

is there way correct or usable iprincipal in code ran task in controller action?

the httpcontext.current.user temporary threadlocal. such, you'll need retrieve it's value before starting task run in different thread. there's no way find out thread has executed task.factory.startnew , retrieve it's threadlocal values. consider, once task.factory.startnew webrequest may end before task has started. need along lines of:

iprincipal principal = httpcontext.current.user;  task.factory.startnew( () => {     myservice.executemethod(principal); } ); 

now if iprincipal (ctor-)injected myservice and myservice instantiated per request (.intransientscope(), .inrequestscope()) current binding work, since controller instanciated each request (also see lifecycle of asp.net mvc5 application).

the problem arise when injecting lazy<iprincipal> or when doing iresolutionroot.get<iprincipal> (this includes usage of ninject.extensions.factory, func<iprincipal>!), because @ point httpcontext.current.user may not valid more.

i suggest if want answer more precise , more point, need post minimal, complete, , verifiable example


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -