Search code examples
c#asp.net-corecontrollerreadonly.net-8.0

Microsoft.AspNetCore.Mvc.ControllerBase.User: Property or indexer 'ControllerBase.User' cannot be assigned to -- it is read only


I am attempting to fix code after updating framwork from .net 4.8 framework to .net8. I am dealing with an issue in my code here :

controller.User = new GenericPrincipal(new GenericIdentity("test"), new[] { Roles.VirtualUser });

Where controller.User is apparently readonly. This is what User looks like in the namespace Microsoft.AspNetCore.mvc:

 /// <summary>
 /// Gets the <see cref="ClaimsPrincipal"/> for user associated with the executing action.
 /// </summary>
 public ClaimsPrincipal User => HttpContext?.User!;

I am not sure what is causing this code to break. I have read though the similar posts but I dont believe any of them have the exact problem. I have seen I could need a setter method, but dont believe I can edit the library code. Any suggestions / tips would be greatly appreciated. Thanks!


Solution

  • You can use one from the ControllerBase.HttpContext. For example in the controller's action:

    HttpContext.User = 
       new GenericPrincipal(new GenericIdentity("test"), new[] { Roles.VirtualUser });