0

I have this code to set Thread.CurrentPrincipal :

    var claims = new List<System.Security.Claims.Claim>();
    //set Active Customer Id
    claims.Add(new Claim("id",100, ClaimValueTypes.Integer32));
    var claimsIdentity = new ClaimsIdentity(claims);
    //Set the principal to a new generic principal.
    Thread.CurrentPrincipal = new ClaimsPrincipal(claimsIdentity);

and this code to retrieve data from Thread.CurrentPrincipal :

 var principal = Thread.CurrentPrincipal as ClaimsPrincipal;
 var id= principal.Claims.Where(c =>
 c.Type == "id")?.Select(x => long.Parse(x.Value)).FirstOrDefault();

When I run my code :

    //retrieve id from principal
    var id1 = identityService.GetBaseEntityProps();
    //add product
    await Product.Add(new Product() { Namt = "test"});
    //save change
    await unitOfWork.SaveChangesAsync();
    //call previous method for retrieve id
    //but its null!
    var id2 = identityService.GetBaseEntityProps();

id1 has value, but when I call method for second time id2 is null...

How can I fix this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Keivan
  • 173
  • 2
  • 12
  • If that question would be about any ASP.Net than it is expected behavior as there is zero guarantees that execution continues on the same thread (same request is expected, unless one uses `ConfigureAwait(false)` )… but should work fine for WinForms/WPF for example... Consider [edit] the question to clarify where do you use that code. – Alexei Levenkov Oct 03 '19 at 17:10
  • @AlexeiLevenkov my project is web api .net core, I set Thread. CurrentPrincipal whit some data like user id and ... after user login. in my service layer, when I fetche data form Principal, its ok. but after save some data to db in ef and fetche Principal data for second data, it's empty! – Keivan Oct 03 '19 at 17:41
  • Answer to your question is there - https://stackoverflow.com/questions/31346574/setting-thread-currentprincipal-with-async-await (also turned out that I misremembered that ASP.Net preserves this particular property of Thread while newer once for web may not... ) – Alexei Levenkov Oct 03 '19 at 18:16

0 Answers0