如何让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,它会返回它。
我该如何解决这个问题?
您应该重写OnAuthorization方法,该方法使用IsAuthorized并刷新响应,或强制刷新您的方法。 – Fals
如何刷新响应,因此我无法找到该功能/选项。 –
是的,我查了一下,他们把.End()远离了Http命名空间。您应该重写OnAuthorization,然后更有意义地填充响应。 – Fals