我需要在Controller
和CustomFilterAttribute
中的AjaxRequest
事件中抛出HttpException
。
当我在Controller
中抛出带有403
错误的Exception
时。
[HttpPost]
[CustomAuthorize]
public ActionResult AjaxSelectBinding()
{
// 403 Error code
throw new HttpException((int)HttpStatusCode.Forbidden, "Forbidden");
}
在客户端脚本中,我总是得到结果代码 - 500
$.ajax({
type: 'POST',
url: '/Groups/AjaxSelectBinding',
success: function(data) {
},
error: function (xhr, ajaxOptions, thrownError) {
// HERE I GET ALWAYS 500 ERROR CODE
}
});
我如何在我的FilterAttribute
中抛出HttpException
并在客户端页面获取此代码。我尝试这样做,但我得到了200
状态码:
public class CustomAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
SharedControllerBase ctrl = (SharedControllerBase)filterContext.Controller;
if (!ctrl.User.Identity.IsAuthenticated &&
filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
}
当我在FilterAttribute
中尝试抛出Exception
时,我再次获得500
状态码。
HttpStatusCode.Unauthorized
错误时进行重定向,因为在客户端中,这种情况下我会得到登录页面和 200(成功)的结果。我想在错误的 ajax 函数回调中翻译我的自定义代码,但是 Web 服务器总是通知我 500 状态码。在控制器中,我可以捕获 2 个异常(访问和内部错误),在客户端代码中我需要将其翻译。 - Kronos