gpt4 book ai didi

c# - Web API AuthorizeAttribute 不返回自定义响应

转载 作者:行者123 更新时间:2023-11-30 13:55:57 25 4
gpt4 key购买 nike

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

在我的 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 处理,而应由 HandleUnauthorizedRequest 处理。我不确定将其放入 OnAuthorization 是否会导致任何重大问题,但大概是因为基类在 中覆盖了您的响应>处理未经授权的请求

这是一件微妙的事情,但 OnAuthorization 指向 HandleUnauthorizedRequest 是有原因的。它主要是职责分离,但如果您想要做的不仅仅是发送错误消息,例如记录错误请求,您的 OnAuthorization 方法可能会变得拥挤。为清楚起见,您应该使用提供给您的方法。

关于c# - Web API AuthorizeAttribute 不返回自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com