ASP.NET Core 7.0 Web 使用中间件验证用户Session
•
算法结构
中间件,直白的说,就是每一次请求到达服务器,先执行的一部分代码。
比如你请求 http://localhost/account,你的请求已经到达了服务器,在服务器执行account这部分代码之前,先执行中间件代码。中间件可以控制你的请求是否允许继续或中断,或转向特定结果。
使用中间件验证用户Session,可以实现全局效果,不用在每个控制器验证,或者做个基类控制器验证。
1、首先,创建一个中间件类文件,SpMiddleware (类名自定义)
#注意判断逻辑中防止死循环
public class SpMiddleware
{
private readonly RequestDelegate _next;
public SpMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
string s = httpContext.Request.Path;
byte[] result;
httpContext.Session.TryGetValue("uname", out result);
//类似访问登录页面的直接通过
if(s=="/Access/Login")
{
await _next(httpContext);
}
else
{
//非登录页面,判断是否已经存在Session键值,如果不存在,跳转到登录页面,你也可以返回其他信息
if (result == null)
{
string loginhtml = "window.location.href='/Access/Login'";
await httpContext.Response.WriteAsync(loginhtml);
}
else //如果存在Session键值,通过请求
{
await _next(httpContext);
}
}
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class SpMiddlewareExtensions
{
public static IApplicationBuilder UseSpMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
2、在Program.cs中,在app.Run()之前添加Use中间件
app.UseMiddleware(); app.Run();
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/c5f8056dd8.html
