派生的 HttpUnauthorizedResult 中未调用 ExecuteResult 方法 class

ExecuteResult method not called in HttpUnauthorizedResult derived class

我需要使用 ASP.NET MVC 3 实现摘要身份验证。为此,我继承了 AuthorizeAttribute 和 HttpUnauthorizedResult。代码如下:

[AttributeUsage ( AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true )]
public class SessionAuthorize: AuthorizeAttribute {
    public override void OnAuthorization ( AuthorizationContext actionContext ) {
        try {
            if ( null != actionContext.HttpContext.Request.Headers["Authorization"] )
                // authorization is on the way
                // <...>
            else
                actionContext.Result = new HttpDigestUnauthorizedResult ();
        } catch ( Exception ex ) {
            Trace.TraceWarning ( "SessionAuthorize.OnAuthorization failed: {0}", ex.Message );
        }
        base.OnAuthorization ( actionContext );
    }
}

public class HttpDigestUnauthorizedResult: HttpUnauthorizedResult {
    public HttpDigestUnauthorizedResult () : base () {
    }
    public override void ExecuteResult ( ControllerContext context ) {
        if ( context == null )
            throw new ArgumentNullException ( "context" );
        // this is supposed to initialize digest authentification exchange
        context.HttpContext.Response.AddHeader ( "WWW-Authenticate", string.Format ( "Digest realm=\"somerealm\",qop=\"auth\",nonce=\"{0}\",opaque=\"{1}\""/*, <...>*/ ) );
        base.ExecuteResult ( context );
    }
}

controller/action的代码如下:

public class DefaultController: Controller {
    [SessionAuthorize]
    public ViewResult Index () {
        return View ();
    }
}

所以它没有做任何特别的事情。

但是,永远不会调用覆盖的 ExecuteResult,并且只会返回标准的 401 页面。我在这里错过了什么? ExecuteResult 应该从哪里调用?

正确的模式是:使用AuthorizeCore(that returns a bool)判断当前请求是否被授权,并在[=13中处理那些未授权的请求=] 方法。将所有内容都放在 OnAuthorization 中是不正确的,因为根据 the source code,在某些情况下会调用 OnCacheAuthorization 方法而不是 OnAuthorization

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    if (httpContext.Request.Headers["Authorization"] == null)
    {
        return false;
    }

    return base.AuthorizeCore(httpContext);
}

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new HttpDigestUnauthorizedResult();
}