0

我从 AuthorizeAttribute 类派生并制作了自己的 CustomAuthorize

  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.HttpContext.Response.StatusCode = 401;
            filterContext.Result = new JsonResult
            {

                Data = new DataSourceResult { Errors = new { error = "NotAuthorized" } }
                ,JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
          // this is a standard request, let parent filter to handle it
           base.HandleUnauthorizedRequest(filterContext);
        }
    }

我在很多地方都在使用 Ajax Jquery 调用,并且检查每个地方的响应然后执行

window.location.href='/Auth/login';

我只是想知道,我们可以从 HandleUnauthorizedRequest 方法重定向到登录页面吗?

4

1 回答 1

0

创建一个基本控制器,您可以在其上放置自定义授权属性。就像是:

[YourAuthorizeAttribute]
public class BaseAuthorizeController : BaseController
{
    public BaseAuthorizeController() {}
}

以上将应用于您的所有操作,而不仅仅是 ajax 操作。对于不需要新逻辑的操作,您可以通过将布尔值传递给 false 来扩展属性;

public class ClaimsAuthorizeAttribute : ActionFilterAttribute
{
    private readonly bool authorize = true;public YourAuthorizeAttribute(bool authorize = true)
    {
        this.authorize = authorize;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!authorize)
        {
            return;
        }

        // Your custom authentication logic
    }
于 2016-11-22T15:09:00.917 回答