How to execute custom HTTP status code during Ajax request (Post)

I need to throw an HttpException during an AjaxRequest in Controller and CustomFilterAttribute

When I throw an Exception in Controller with error 403

 [HttpPost] [CustomAuthorize] public ActionResult AjaxSelectBinding() { // 403 Error code throw new HttpException((int)HttpStatusCode.Forbidden, "Forbidden"); } 

In the client script, I always get the result code - 500

  $.ajax({ type: 'POST', url: '/Groups/AjaxSelectBinding', success: function(data) { }, error: function (xhr, ajaxOptions, thrownError) { // HERE I GET ALWAYS 500 ERROR CODE } }); 

How can I throw an HttpException in my FilterAttribute and get this code on the client page. I try to do this, but I get a 200 status code:

 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; } } 

When I try to throw an Exception on FilterAttribute , I get a 500 status code again

+6
source share
1 answer

First things first, HttpStatusCode.Unauthorized = 401 , not a 403 status code. There is an important difference between the two codes.

When you set the status code to 401, some unpleasant things happen: you are automatically redirected to the login page using the ASP.NET Forms authentication module => the login page is provided with the status code = 200. Phil Haack addressed this issue in the post blog post .

Regarding throw new HttpException((int)HttpStatusCode.Forbidden, "Forbidden"); in the action of your controller, you selected an exception of type HttpException and whose StatusCode is set to 401, but apart from it absolutely nothing will catch this exception and set the corresponding response status code. Thus, the exception is bubbling up, and since you do not seem to have a global exception handler, it is translated as a page with a 500 error to the server.

Here's an example of a global exception handler that might come in handy.

+6
source

Source: https://habr.com/ru/post/902820/


All Articles