Web API AuthorizeAttribute不返回自定义响应

时间:2015-06-17 15:54:20

标签: 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;
        }
    }

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

如何解决此问题?

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

您应该覆盖OnAuthorization方法,使用IsAuthorized并刷新response,或强制刷新方法。更有意义填充过滤器操纵它的响应。

答案 2 :(得分:1)

是的,我同意。您需要实现从AuthorizeAttribute派生的自定义过滤器。

protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
    base.HandleUnauthorizedRequest(actionContext);
    actionContext.Response = new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.Unauthorized,
        Content = new ObjectContent(typeof(ErrorMessage),
        new ErrorMessage()
        {
            StatusCode = (int)HttpStatusCode.Unauthorized,
            Message = Constants.UnauthorisedErrorMessage,
            ErrorCode = Constants.UnauthorisedErrorCode
        }, new JsonMediaTypeFormatter())
    };
}