在ASP.NET Core MVC/WebAPI中,可以使用认证方案加匿名访问来实现身份验证和匿名访问的控制。下面是一种实现方法的示例代码:
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // 登录页面的路径
options.AccessDeniedPath = "/Account/AccessDenied"; // 拒绝访问页面的路径
});
// 添加授权策略
services.AddAuthorization();
// 其他服务的注册...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// 其他中间件的配置...
// 启用身份验证和授权中间件
app.UseAuthentication();
// 其他中间件的配置...
}
[Authorize]
public IActionResult SecureAction()
{
// 代码逻辑...
}
[AllowAnonymous]
public IActionResult PublicAction()
{
// 代码逻辑...
}
使用这种方式,被标记为[Authorize]的Action将需要用户登录才能访问,而被标记为[AllowAnonymous]的Action则可以匿名访问。