我们提供安全,免费的手游软件下载!
本文将介绍在 Blazor 静态服务端呈现(静态 SSR)模式下,用户登录身份认证的实现方式。
SSR(Server-Side Rendering)指的是服务器侧呈现。HTML 是由服务器上的 ASP.NET Core 运行时生成,通过网络发送到客户端,供客户端的浏览器显示。SSR 分为两种类型:
由于交互式 SSR 存在断线重连的问题,影响用户体验。因此,采用静态 SSR 组件呈现服务端内容,增加前端交互体验,采用 JavaScript 作为前端交互的解决方案。
public class UserInfo
{
public string UserName { get; set; }
}
public class Context
{
public UserInfo CurrentUser { get; set; }
}
@code {
[CascadingParameter] private HttpContext HttpContext { get; set; }
private UserInfo user;
protected override void OnInitialized()
{
base.OnInitialized();
if (HttpContext.User.Identity.IsAuthenticated)
user = new UserInfo { UserName = HttpContext.User.Identity.Name };
else
user = null;
}
}
@code {
private UIContext context;
[Parameter] public UserInfo User { get; set; }
protected override void OnInitialized()
{
context = new Context();
context.CurrentUser = User;
base.OnInitialized();
}
}
@if (Context.CurrentUser == null)
{
登录
}
else
{
退出
}
@code {
[CascadingParameter] private Context Context { get; set; }
}
public class AuthController : ControllerBase
{
private const string AuthType = "App_Cookie";
[Route("signin")]
public async Task Login([FromBody] UserInfo info)
{
var claims = new List() { new(ClaimTypes.Name, info.UserName) };
var identity = new ClaimsIdentity(claims, AuthType);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(AuthType, principal);
}
[Route("signout")]
public async Task Logout()
{
await HttpContext.SignOutAsync(AuthType);
}
}
相关资讯
热门资讯