2015-06-17 34 views
0

如何让IsAuthorized返回我的自定义对象,同时函数返回false?Web API AuthorizeAttribute不返回自定义响应

在我的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,它会返回它。

我该如何解决这个问题?

+1

您应该重写OnAuthorization方法,该方法使用IsAuthorized并刷新响应,或强制刷新您的方法。 – Fals

+0

如何刷新响应,因此我无法找到该功能/选项。 –

+1

是的,我查了一下,他们把.End()远离了Http命名空间。您应该重写OnAuthorization,然后更有意义地填充响应。 – Fals

回答

1

您应该重写OnAuthorization方法,该方法使用IsAuthorized并刷新response或强制刷新您的方法。更有意义的填充过滤器处理它的响应。

2

我知道这个问题已经回答,但我觉得它有点不对。我认为未经授权的请求的消息不应该由OnAuthorization来处理,但应该由HandleUnauthorizedRequest来处理。我不确定它是否会导致将它放在OnAuthorization中的任何主要问题,但可能是因为您在真实和非虚假时收到消息的原因是因为基类将您的响应写入HandleUnauthorizedRequest

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

相关问题