How do I access HttpContext in Server-side Blazor?

后端 未结 4 1900
感动是毒
感动是毒 2020-12-06 00:40

I need to access HttpContext in a page (.cshtml) and in particular a request and then a cookie. Despite available, HttpContextAccessor always has

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 00:59

    It depends what you want to access the HttpContext for.

    Should you want to access authentication or user info, consider using the AuthenticationStateProvider instead:

    @page "/"
    @using System.Security.Claims
    @using Microsoft.AspNetCore.Components.Authorization
    @inject AuthenticationStateProvider AuthenticationStateProvider
    
    

    ClaimsPrincipal Data

    @_authMessage

    @if (_claims.Count() > 0) {
      @foreach (var claim in _claims) {
    • @claim.Type – @claim.Value
    • }
    }

    @_surnameMessage

    @code { private string _authMessage; private string _surnameMessage; private IEnumerable _claims = Enumerable.Empty(); private async Task GetClaimsPrincipalData() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity.IsAuthenticated) { _authMessage = $"{user.Identity.Name} is authenticated."; _claims = user.Claims; _surnameMessage = $"Surname: {user.FindFirst(c => c.Type == ClaimTypes.Surname)?.Value}"; } else { _authMessage = "The user is NOT authenticated."; } } }

提交回复
热议问题