实现需求:验证Token是否有效,重写状态码和返回内容
/// <summary> /// 权限过滤器,验证Token是否有效 /// </summary> /// <param name="filterContext"></param> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.HttpContext.Response.StatusCode = 403; string token = filterContext.HttpContext.Request.Headers["token"]; if (string.IsNullOrWhiteSpace(token)) { filterContext.Result = new JsonResult { Data = new { IsSuccess = false, Message = "权限验证失败!" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } return; }
返回内容
2、重写AuthorizeCore,实现权限验证
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (string.IsNullOrEmpty(httpContext.Request.Headers["token"])) { httpContext.Response.StatusCode = 401;//无权限状态码 return false; } return true; }
标签:filterContext,return,string,C#,token,MVC,过滤器,httpContext,权限 From: https://www.cnblogs.com/work-code/p/16869044.html