所以我想做的是编写一些 ASP.NET Core 中间件来授权用户,然后他才能看到视图的内容。
我正在为我的会话使用 Microsoft.AspNetCore.Session 包。
中间件的内容:
//simplified code that should check if the Session is valid
if (HttpContext.Session.GetString("xyz") == null)
{
//Return to Login View;
}
//else (when the session is valid) return to the view that the user whants to view.
不明白的地方:
看来你走对了。中间件是在允许用户访问特定视图之前处理授权过程的好方法。这是帮助您实现目标的分步指南:
1.创建自定义中间件类:
public class AuthorizationMiddleware
{
private readonly RequestDelegate _next;
public AuthorizationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Check if the session is valid
if (context.Session.GetString("xyz") == null)
{
// Redirect to the Login view
context.Response.Redirect("/Account/Login");
return;
}
// Call the next middleware in the pipeline
await _next(context);
}
}
2.创建中间件扩展:
public static class AuthorizationMiddlewareExtensions
{
public static IApplicationBuilder UseAuthorizationMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AuthorizationMiddleware>();
}
}
3.在Startup.cs文件中注册中间件:
首先,通过修改.csproj文件,将Microsoft.AspNetCore.Session包添加到你的项目中:
<ItemGroup>
...
<PackageReference Include="Microsoft.AspNetCore.Session" Version="2.2.0" />
...
</ItemGroup>
然后,在Startup.cs文件中:
一个。添加 app.UseSession();配置方法中的行:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseSession(); // Add this line
app.UseAuthorizationMiddleware(); // Add this line to use your custom middleware
app.UseEndpoints(endpoints =>
{
...
});
}
b。在 ConfigureServices 方法中添加以下内容以启用会话处理:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDistributedMemoryCache(); // Add this line
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
}); // Add this line
...
}
现在,您的自定义中间件应该按预期工作,检查会话是否有效,并在需要时将用户重定向到登录页面。请记住从中间件中排除登录和注册页面以避免重定向循环。
作为旁注,重要的是要提到 ASP.NET Core 有一个您可能会考虑使用的内置身份验证和授权系统,它可以简化您的代码并提供更标准化的解决方案。您可以在官方文档中查看:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs=visual-studio