繁体   English   中英

Blazor 应用服务器 - 在类似于 asp.net 核心 Mvc 的 blazor 中使用声明?

[英]Blazor App Server - Using Claims in a blazor similar to asp.net core Mvc?

我在 Blazor 中使用了这个代码:

 if (UserAccont.LoginUser(loginuser) != null)
        {
            if (UserAccont.UserIsBlocked(loginuser.Mobile)) 
            {
                UserIsBlocked = true;
            }
            else
            {
                var user = UserAccont.LoginUser(loginuser);
                var claims = new List<Claim>()
                {
                  new Claim(ClaimTypes.Name,user.Mobile.ToString()),
                };
                var identity = new ClaimsIdentity(claims, 
                 CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);
                var properties = new AuthenticationProperties
                {
                    IsPersistent = true

                };
                 HttpContext.SignInAsync(principal, properties);
            }
        }

但是 HttpContext 是用于 mvc

我如何使用此代码?

我不能在 razor 视图中使用它吗?

 @if (User.Identity.IsAuthenticated)

请帮我?

但是 HttpContext 是用于 mvc 我如何使用此代码? 我不能在 razor 视图中使用它?

 @if (User.Identity.IsAuthenticated)

From your code and description, it seems that you are creating an Asp.net Core Blazor server application with cookie Authentication, and now you want to check whether the user is Authenticated or not in the Razor page or Razor component, right?

要在 Blazor 页面中获取当前用户详细信息,我们需要注入依赖IHttpContextAccessor

首先,我们需要在startup.cs中配置IHttpContextAccessor服务,如下所示。

  services.AddHttpContextAccessor();

然后,在 Blazor 组件中,参考以下方法检查用户是否通过身份验证:

@page "/"
@using Microsoft.AspNetCore.Http;
@inject IHttpContextAccessor httpContextAccessor
<h1>Hello, world!</h1>

Welcome to your new app.
<br />

@if (httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
    <span> You have authenticated! </span>
}
<br />
@message

<SurveyPrompt Title="How is Blazor working for you?" />

@code{
    private string message;

    protected override void OnInitialized()
    {
        if (httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
            message = $"Initialized at {DateTime.Now}";
    }
}

结果如下:

在此处输入图像描述

有关使用 Cookie 身份验证创建 Blazor 服务器端应用程序的更多详细信息,您可以参考此示例:简单服务器端 Blazor Cookie 身份验证的演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM