我本来希望它返回“真”或“假”...
我已经在我的控制器中覆盖了 OnAuthorization 并且基于丢失或无效的 HTTP 标头值我想返回 403 禁止,但是我似乎无法弄清楚如何从 OnAuthorization 返回任何内容,以便它实际上会停止控制器的其余部分从运行。
我该怎么办?
我在下面的第一次尝试是一个巨大的失败,我认为 Deny() 正在运行但没有任何反应......
public class AuthController : Controller
{
protected override void OnAuthorization(AuthorizationContext filterContext)
{
if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
Deny();
string authString = filterContext.HttpContext.Request.Headers["Authorization"];
base.OnAuthorization(filterContext);
}
private ActionResult Deny()
{
HttpContext.Response.StatusCode = 403;
return Content("Access Denied", "text/plain");
}
}
UPDATE看起来像这样成功了,为什么这可能是一个不好的方法?
if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
{
filterContext.Result = Content("Access Denied", "text/plain");
filterContext.HttpContext.Response.StatusCode = 403;
base.OnAuthorization(filterContext);
}
再次更新好的,所以现在它根本不起作用......我放了一个断点,看着它进入那个 if 语句,然后进入 base.OnAuthorization(...) 调用,然后再次退出......如果它没有执行,为什么它会进入 if 语句?如果它正在执行,为什么调用 base.OnAuthorization(...) 不会提前结束?