Web API AuthorizeAttribute不返回自定义响应

Teo*_*ahi 3 c# asp.net-web-api asp.net-mvc-5

当函数返回false时,如何让IsAuthorized返回我的自定义对象?

在我的WebAPI项目中,我有一个类;

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {

            StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse()
                    {
                        code = (int) Constants.ErrorCodes.InvalidCredentials,
                        data = "InvalidCredentials.",
                        StatusCode = HttpStatusCode.Unauthorized
                    };
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                        invalidUserResponse);
                    // if I set this to true I am getting 401 with my custom object
                    // otherwise it gives me default error message 
                    // {"Message":"Authorization has been denied for this request."}
                    return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当我从IsAuthorized函数返回false时,它不会返回我的自定义invalidUserResponse对象.但是,如果我返回true,它将返回它.

我该如何解决这个问题?

Ten*_*ude 5

我知道这个问题已得到解答,但我觉得这有点不对劲.我不认为应该处理未经授权的请求的消息,OnAuthorization但应该由处理HandleUnauthorizedRequest.我不确定它是否会导致出现任何重大问题OnAuthorization,但可能是因为基类会在你的响应中写入错误而得到消息的原因HandleUnauthorizedRequest.

这是一个微妙的事情,但OnAuthorization指向HandleUnauthorizedRequest一个原因.它主要是责任分离的事情,但如果你想做的不仅仅是发送错误信息,比如记录错误请求你的OnAuthorization方法可能会变得拥挤.为了清楚起见,你应该使用给你的方法,如果没有别的.