Search code examples
c#razorblazor

Passing UserId from blazor page


I am abolutely new to blazor so be gentle with me :). In my app there is button which sends POST request to server. The endpoint that is called does a bunch of things, but I need to get Id of currently signed in user. So I am passing it with the request. Everytime request comes through the result is System.Threading.Tasks.Task`1[System.String]. I have no idea what I'm doing wrong I know it has to do something with my methods being asynchronous, but after few hours of try and errors I'm helpless.

Does anybody know why am I getting the wrong value? And is there any better way to pass the Id of the user? I feel like my solution is not ideal.

Thanks a lot!

My .razor is:

@page "/Overview"
<AuthorizeView>
    <Authorized>
        <div class="btn btn-warning btn-sm" style="border-color:black" @onclick="SyncTrades">Sync trades</div>

    </Authorized>
    <NotAuthorized>
        You are not signed in. Please sign in.

    </NotAuthorized>
</AuthorizeView>

@using BlazorPro.Spinkit
@using System.Net.Http.Json
@inject HttpClient Http
@using System.Security.Claims
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider


@code {
    protected async Task SyncTrades()
    {
        var userId = GetUserId().ToString();
        await Http.PostAsync("https://localhost:44366/api/SyncTrades/" + userId, new StringContent(""));
    }

    private string _authMessage;
    private string _surnameMessage;
    private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>();

    private async Task<string> GetUserId()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        return user.Claims.FirstOrDefault().Value;
    }

}

My controller post method

// POST api/<SyncTradesController>
    [HttpPost("{UserId}")]
    //public void Post([FromRoute]string UserId)
    public async Task Post([FromRoute] string UserId)
    {
        DoStuff();
    }

Solution

  • You should await the GetUserId() call since it's an asynchronous method:

        protected async Task SyncTrades()
        {
            var userId = await GetUserId(); //.ToString() is redundant here
            await Http.PostAsync("https://localhost:44366/api/SyncTrades/" + userId, new StringContent(""));
        }
    

    For clarity it's advised to postfix Task (or Task<T>) returning methods with Async -> GetUserIdAsync().

    An (better) alternative would be to pass the UserId via headers.There are multiple alternatives but that's a whole other world!

    Regarding authentication; you could start reading here: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-5.0#blazor-server-authentication