.NET Core授权失败自定义响应信息的操作方法(2)

public class CustomAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler { public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult) { var endPoint = context.GetEndpoint(); var controllerActionDescriptor = (ControllerActionDescriptor)endPoint.Metadata .ToList().FirstOrDefault(d => d is ControllerActionDescriptor); var controllerName = controllerActionDescriptor.ControllerName; var actionName = controllerActionDescriptor.ActionName; if (!context.User.Identity.IsAuthenticated) { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await context.Response.WriteAsync("{\"data\":{\"succeeded\":false,\"code\":401,\"message\":\"登录已过期,请重新登录\"}}"); return; } else if (!await HandleRequirementEvaluateAsync(context.User, controllerName, actionName)) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; await context.Response.WriteAsync("{\"data\":{\"succeeded\":false,\"code\":403,\"message\":\"您暂无足够的权限执行该操作\"}}"); return; } await next(context); } }

自从.NET 5有了IAuthorizationMiddlewareResultHandler授权中间件接口,一切又是那么得心应手!

到此这篇关于.NET Core授权失败如何自定义响应信息的文章就介绍到这了,更多相关.NET Core自定义响应信息内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyfdgx.html