授权策略扩展 [Authorize]
您可以使用授权策略来做到这一点。在 Startup.cs 内的 ConfigureServices(IServiceCollection services) 中配置这些,如下所示:
services.AddAuthorization(options =>
{
// Create your own policy and make the "access checks" in there
options.AddPolicy("MyAccessPolicy", policy => policy.RequireAssertion(httpCtx =>
{
if (access checks...)
return true;
else
return false;
}));
});
然后你只需像这样用Authorize 属性装饰你的控制器动作:
[Authorize(Policy = "MyAccessPolicy")]
public IActionResult Access()
{
return View();
}
现在,无论您何时尝试访问 /access,此策略都会运行,如果该策略返回 false,用户将看到 HTTP 403(禁止访问)状态代码。
自定义中间件映射到路由
作为对您的评论的回应,这里有一个中间件示例以及如何将其映射到特定路由。
我自己的项目中的一个示例,其中包含一个全局错误处理中间件(去掉了一些不相关的部分):
public class ExceptionHandlingMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
// Call next middleware
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception ex)
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
ErrorDetails error = null;
if (ex is FileNotFoundException || ex is DirectoryNotFoundException)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
error = _localizer.FilesOrFoldersNotFound();
}
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(
new CustomResponse(false, error ?? _localizer.DefaultError()),
_serializerSettings));
}
}
要仅将此中间件用于特定路由,您可以这样做as suggested here:
// Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Map("path/where/error/could/happen",
b => b.UseMiddleware<ExceptionHandlingMiddleware>());
// ...
}
或者检查中间件内部的路径:
// ExceptionHandlingMiddleware.cs
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (!context.Request.Path.StartsWithSegments("path/where/error/could/happen"))
{
// Skip doing anything in this middleware and continue as usual
await next(context);
return;
}
// Use middleware logic
try
{
// Call next middleware
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}