当前位置: 首页> 健康> 美食 > 云南网站建设优化技术_珠海做网站设计_视频剪辑培训_最有创意的广告语30条

云南网站建设优化技术_珠海做网站设计_视频剪辑培训_最有创意的广告语30条

时间:2025/7/12 2:14:37来源:https://blog.csdn.net/knownchen/article/details/142315549 浏览次数:0次
云南网站建设优化技术_珠海做网站设计_视频剪辑培训_最有创意的广告语30条

本文介绍 Blazor 静态服务端呈现(静态 SSR)模式下,用户登录身份认证是如何实现的。

1. SSR 简介

SSR 是服务器侧呈现,HTML 是由服务器上的 ASP.NET Core 运行时生成,通过网络发送到客户端,供客户端的浏览器显示。SSR 分两种类型:

  • 静态 SSR:服务器生成静态 HTML,它不提供用户交互性或维护 Razor 组件状态,通过 HTTP 协议进行通信。
  • 交互式 SSR:Blazor 事件允许用户交互,并且 Razor 组件状态由 Blazor 框架维护,通过 SignalR 连接使用 WebSocket 协议进行通信。

2. 为什么用静态 SSR

由于交互式 SSR 存在断线重连的问题,影响用户体验,所以采用静态 SSR 组件呈现服务端内容,为了增加前端交互体验,采用 JavaScript 作为前端交互。

3. 实现思路

  • 在 App.razor 文件中使用级联参数的 HttpContext 对象获取用户是否登录
  • 将用户登录信息传递给路由组件的级联 Context 对象,
  • 在所有子组件中,使用级联参数的 Context 对象获取用户信息
  • 使用 HttpContext.SignInAsync 和 HttpContext.SignOutAsync 实现登录和注销

4. 实现步骤

  • 创建 UserInfo 和 Context 类
public class UserInfo
{public string UserName { get; set; }
}public class Context
{public UserInfo CurrentUser { get; set; }
}
  • 创建 App.razor 文件
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8" />
</head>
<body><Routes User="user" />
</body>
</html>@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 };elseuser = null;}
}
  • 创建 Route.razor 文件
<CascadingValue Value="context" IsFixed><Router AppAssembly="typeof(Program).Assembly"><Found Context="routeData"><RouteView RouteData="routeData" /></Found><NotFound></NotFound></Router>
</CascadingValue>@code {private UIContext context;[Parameter] public UserInfo User { get; set; }protected override void OnInitialized(){context = new Context();context.CurrentUser = User;base.OnInitialized();}
}
  • 创建 LoginBox.razor 文件
@if (Context.CurrentUser == null)
{<span onclick="login()">登录</span><script>function login() { fetch('/signin').then(res => location.reload()); }</script>
}
else
{<span onclick="logout()">退出</span><script>function logout() { fetch('/signout').then(res => location.reload()); }</script>
}@code {[CascadingParameter] private Context Context { get; set; }
}
  • 创建 AuthController.cs 文件
public class AuthController : ControllerBase
{private const string AuthType = "App_Cookie";[Route("signin")]public async Task Login([FromBody] UserInfo info){var claims = new List<Claim>() { 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);}
}
关键字:云南网站建设优化技术_珠海做网站设计_视频剪辑培训_最有创意的广告语30条

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: