Asp.Net MVC HTTP错误401.0 - 未经授权

时间:2014-04-15 15:33:45

标签: asp.net-mvc error-handling authorization claims-based-identity claims

我有一个MVC应用程序,它使用声明授权,基于可用的优秀教程here。在代码中,我覆盖ClaimsAuthorizationManager的CheckAccess方法,以针对每个资源和操作实现我自己的逻辑

public class CustomAuthorisationManager : ClaimsAuthorizationManager
{
    public override bool CheckAccess(AuthorizationContext context)
    {
        string resource = context.Resource.First().Value;
        string action = context.Action.First().Value;

        if (action == "Show" && resource == "Code")
        {
            bool livesInScotland = context.Principal.HasClaim(ClaimTypes.Country, "Scotland");
            return livesInScotland;
        }

        return false;
    }
}

一切正常,除了每当CheckAccess方法返回false时,我得到HTTP错误401.0 - 未经授权,我读过的只能由IIS处理。我的问题是,如何在代码中处理此错误以向用户显示自定义错误页面。我见过许多不同的解决方案,例如herehere,但从未设法让它对我有效。

1 个答案:

答案 0 :(得分:0)

您可以实施IHttpModule。可以找到实施一个指南here。关于httpmodule的好处是你几乎可以捕获任何HTTP响应并用它做你想做的事。

或者您可以查看this SO question。也许你会更喜欢它。