Upload Controller and SecurityService

I used the upload control to allow the user to upload the file to the website. I'm able to parse the file coming in (CSV) by creating a method and setting a route on the UploadController, but my problem is that one of my fields in my data model that I'm trying to save is the UserId, which I need to get from the SecurityService. I tried to inject the SecurityService into the UploadController constructor, but when I try to access the User property, I get the following error:

"GetAuthenticationStateAsync was called before SetAuthenticationState."

I assumed that if I injected the SecurityService into the UploadController created by the Radzen Blazor code generator, that I'd be able to access the current user, but that doesn't appear to be working. I commented the line below that is causing the exception.

public partial class UploadController : Controller
{

    private readonly SchedulingContext context;
    private readonly NavigationManager navigationManager;
    private readonly SecurityService security;

    public UploadController(SchedulingContext context, NavigationManager navigationManager, SecurityService security)
    {
        this.context = context;
        this.navigationManager = navigationManager;
        this.security = security;
    }

    // Single file upload
    [HttpPost("upload/single")]
    public IActionResult Single(IFormFile file)
    {
        try
        {
            // this line causes the exception
            string userID = security.User.Id;

            // Put your code here
            return StatusCode(200);
        }
        catch (Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }

Is there a different/better way of doing this? How do I get the current logged in user from within the UploadController?

1 Like

Hi @Arthur_Ardolino,

The SecurityService uses the Blazor AuthenticationStateProvider which may not work in a regular Controller. You can try getting the user from HttpContext.User. There is a good chance it will work.

Yes, HttpContext.User worked. Thank you! I injected an IHttpContextAccessor into the controller and that gave me what I needed.