c# - Set Thread.CurrentPrincipal Asynchronously? -


using asp.net webapi, during authentication, thread.currentprincipal set controllers can later use apicontroller.user property.

if authentication step becomes asynchronous (to consult system), mutation of currentprincipal lost (when caller's await restores synchronization context).

here's simplified example (in real code, authentication happens in action filter):

using system.diagnostics; using system.security.principal; using system.threading; using system.threading.tasks;  public class exampleasynccontroller : system.web.http.apicontroller {     public async task getasync()     {         await authenticateasync();          // await above saved/restored current synchronization         // context, undoing assignment in authenticateasync().          debug.assert(user genericprincipal);     }      private static async task authenticateasync()     {         // save current httpcontext because it's null after await.         var currenthttpcontext = system.web.httpcontext.current;          // asynchronously determine identity.         await task.delay(1000);         var identity = new genericidentity("<name>");          var roles = new string[] { };         thread.currentprincipal = new genericprincipal(identity, roles);         currenthttpcontext.user = thread.currentprincipal;     } } 

how set thread.currentprincipal in async function such caller's await doesn't discard mutation when restoring synchronization context?

you have set httpcontext.current.user well. see this answer , this blog post more info.

update: ensure running on .net 4.5 , have usertaskfriendlysynchronizationcontext set true.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -