Blazor Server - How to get current user in a controller?

Cenk 956 Reputation points
2022-09-25T11:31:02.37+00:00

Hi there,

In my Blazor Server Application, I implemented a controller in order to upload excel files into the server and insert data from this excel into the database. The problem is I am getting this error while trying to get the current user in the controller action.

Error:

System.InvalidOperationException  
  HResult=0x80131509  
  Message=GetAuthenticationStateAsync was called before SetAuthenticationState.  
  Source=Microsoft.AspNetCore.Components.Server  

Here is the Blazor code:

<div class="container-fluid">  
    <div class="row px-3">  
        <div class="col-md-4 p-3">  
<RadzenCard>  
    <h4 class="mb-4">Upload Orders With Excel</h4>  
    <RadzenUpload Url="upload/single" Progress=@TrackProgress Complete=@CompleteUpload class="w-100" />  
    <RadzenProgressBar Value=@progress class="mt-4" Visible=@showProgress />  
    <RadzenLabel Visible=@showComplete class="mt-4" Text="Upload Complete!" />  
</RadzenCard>  
</div>  
 </div>  
</div>  

Here is the controller:

[DisableRequestSizeLimit]  
    public class UploadController : ControllerBase  
    {  
        private readonly IWebHostEnvironment env;  
        private readonly ILogger<UploadController> logger;  
        private readonly IAddOrderListUseCase _addOrderListUseCase;  
        private readonly AuthenticationStateProvider authenticationStateProvider;  
  
        public UploadController(IWebHostEnvironment env,  
        ILogger<UploadController> logger, IAddOrderListUseCase addOrderListUseCase, AuthenticationStateProvider authenticationStateProvider)  
        {  
            this.env = env;  
            this.logger = logger;  
            this._addOrderListUseCase = addOrderListUseCase;  
            this.authenticationStateProvider = authenticationStateProvider;  
  
        }  
  
        // POST: Upload  
        [HttpPost("upload/single")]  
        public async Task<IActionResult> Single(IFormFile file)  
        {  
            try  
            {  
                // Put your code here  
                await UploadFile(file);  
                return StatusCode(200);  
            }  
            catch (Exception ex)  
            {  
                return StatusCode(500, ex.Message);  
            }  
        }  
  
        public async Task UploadFile(IFormFile file)  
        {  
            var user = (await authenticationStateProvider.GetAuthenticationStateAsync()).User;  
            string trustedFileNameForFileStorage;  
            var untrustedFileName = file.FileName;  
  
            var trustedFileNameForDisplay =  
                WebUtility.HtmlEncode(untrustedFileName);  
  
  
            try  
            {  
                trustedFileNameForFileStorage = Path.GetRandomFileName();  
                var path = Path.Combine(env.ContentRootPath,  
                    env.EnvironmentName, "unsafe_uploads",  
                    trustedFileNameForFileStorage);  
  
                await using FileStream fs = new(path, FileMode.Create);  
                await file.CopyToAsync(fs);  
  
                logger.LogInformation("{FileName} saved at {Path}",  
                    trustedFileNameForDisplay, path);  
                //Get file  
                var newfile = new FileInfo(file.Name);  
                var fileExtension = newfile.Extension;  
  
                //Check if file is an Excel File  
                if (fileExtension.Contains(".xls"))  
                {  
                    using var ms = new MemoryStream();  
                    await file.OpenReadStream().CopyToAsync(ms);  
  
  
                    // If you use EPPlus in a noncommercial context  
                    // according to the Polyform Noncommercial license:  
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;  
                    using ExcelPackage package = new ExcelPackage(ms);  
                    var workSheet = package.Workbook.Worksheets["Order"];  
                    var totalRows = workSheet.Dimension.Rows;  
  
                    var orderList = new List<Order>();  
                    List<OrderDetail> orderDetailList = null;  
  
                    var k = 0;  
  
                    for (var i = 2; i <= totalRows; i++)  
                    {  
  
                        if (workSheet.Cells[i, 1].Value != null && workSheet.Cells[i, 2].Value != null)  
                        {  
                            orderDetailList = new List<OrderDetail>();  
                            //Hem order hem detail var  
                            orderList.Add(new Order  
                            {  
                                OrderDateTime = DateTime.Now,  
                                CustomerId = Convert.ToInt32(workSheet.Cells[i, 1].Value),  
                                Status = "Continues",  
                                DoneBy = user.Identity.Name  
  
                            });  
  
                            orderDetailList.Add(new OrderDetail  
                            {  
                                ProductCode = workSheet.Cells[i, 2].Value.ToString(),  
                                ProductName = "",  
                                VendorId = Convert.ToInt32(workSheet.Cells[i, 3].Value),  
                                Quantity = Convert.ToInt32(workSheet.Cells[i, 4].Value),  
                                BuyUnitPrice = Convert.ToDouble(workSheet.Cells[i, 5].Value),  
                                CostRatio = Convert.ToDouble(workSheet.Cells[i, 6].Value),  
                                //UnitCost = Convert.ToDouble(workSheet.Cells[i, 7].Value),  
                                SellUnitPrice = Convert.ToDouble(workSheet.Cells[i, 7].Value),  
                                Status = "Getting Ready",  
                                Description = workSheet.Cells[i, 8].Value.ToString(),  
                                CustomerStockCode = workSheet.Cells[i, 9].Value.ToString(),  
                                CustomerOrderNumber = workSheet.Cells[i, 10].Value.ToString(),  
                                IsActive = 1  
                            });  
  
                            orderList[k].OrderDetails = orderDetailList;  
                            k++;  
  
  
                        }  
                        else if (workSheet.Cells[i, 1].Value == null && workSheet.Cells[i, 2].Value != null)  
                        {  
                            //Sadece detail var  
                            orderDetailList.Add(new OrderDetail  
                            {  
                                ProductCode = workSheet.Cells[i, 2].Value.ToString(),  
                                ProductName = "",  
                                VendorId = Convert.ToInt32(workSheet.Cells[i, 3].Value),  
                                Quantity = Convert.ToInt32(workSheet.Cells[i, 4].Value),  
                                BuyUnitPrice = Convert.ToDouble(workSheet.Cells[i, 5].Value),  
                                CostRatio = Convert.ToDouble(workSheet.Cells[i, 6].Value),  
                                //UnitCost = Convert.ToDouble(workSheet.Cells[i, 7].Value),  
                                SellUnitPrice = Convert.ToDouble(workSheet.Cells[i, 7].Value),  
                                Status = "Getting Ready",  
                                Description = workSheet.Cells[i, 8].Value.ToString(),  
                                CustomerStockCode = workSheet.Cells[i, 9].Value.ToString(),  
                                CustomerOrderNumber = workSheet.Cells[i, 10].Value.ToString(),  
                                IsActive = 1  
                            });  
                            orderList[k - 1].OrderDetails = orderDetailList;  
  
  
                        }  
  
  
                    }  
                    await _addOrderListUseCase.ExecuteAsync(orderList);  
  
                }  
  
            }  
            catch (IOException ex)  
            {  
                logger.LogError("{FileName} error on upload (Err: 3): {Message}",  
                    trustedFileNameForDisplay, ex.Message);  
  
            }  
        }  
  
    }  

How can I get the current user in the controller? I need your help.

Thank you.

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,398 questions
{count} votes

3 answers

Sort by: Most helpful
  1. AgaveJoe 26,141 Reputation points
    2022-09-25T13:25:17.96+00:00

    How can I get the current user in the controller?

    The syntax is below assuming you are using standard authorization and authentication

    User.Identity.Name  
    
    0 comments No comments

  2. ros\\tech 6 Reputation points
    2022-12-07T18:32:54.623+00:00

    i ran into the same issue as well and didn't understand AgaveJoe's answer at first.

    if the controller extends from ControllerBase, there is a member "this.User"

    268258-image.png

    this should do the trick. also helpful: https://stackoverflow.com/questions/38751616/asp-net-core-identity-get-current-user

    cheers

    0 comments No comments

  3. AlexChow 11 Reputation points MVP
    2022-12-07T20:41:27.593+00:00

    Use {this.User.Identity.Name} like this

    namespace My.Controllers  
    {  
      
        [ApiVersion("1")]  
        [Route("api/[controller]")]  
        [ApiController]  
        //[Authorize]  
        // Must be in the Administrator Role  
        [Authorize(Roles = "Administrators,Superuser")]  
        public class UploadController : Controller  
        {  
            private readonly IWebHostEnvironment environment;  
            private readonly ILogger<UploadController> _logger;  
            private readonly IConfiguration _config;  
      
            public UploadController(IWebHostEnvironment environment, ILogger<UploadController> logger, IConfiguration config)  
            {  
                this.environment = environment;  
                this._logger = logger;  
                this._config = config;  
            }  
      
            [HttpPost("[action]")]  
            [RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)]  
            [DisableRequestSizeLimit]  
            public async Task<IActionResult> MultipleAsync(string CurrentDirectory, string filename = null, bool forceJpg = false)  
            {  
      
                try  
                {  
      
                    if (HttpContext.Request.Form.Files.Any())  
                    {  
                        foreach (var file in HttpContext.Request.Form.Files)  
                        {  
                              _logger.LogInformation($"{this.User.Identity.Name} File upload complete {path}");  
                        }  
                        return StatusCode(200);  
                    }  
                    else  
                    {  
                        _logger.LogError($"{this.User.Identity.Name} No files upload");  
                        return StatusCode(202, "No files upload");  
                    }  
                }  
                catch (Exception ex)  
                {  
                    _logger.LogError($"{this.User.Identity.Name} upload error : {ex.Message}");  
                    return StatusCode(500, ex.Message);  
                }  
            }  
    }  
    
    0 comments No comments