Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How throw custom http status code during Ajax(Post) request

I need to throw HttpException during AjaxRequest in Controller and CustomFilterAttribute

When I throw Exception in Controller with 403 error

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

In 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 HttpException in my FilterAttribute and get this code in client page. I try do this, but I get 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 throw Exception in FilterAttribute I get 500 Status Code again

like image 585
Kronos Avatar asked Dec 01 '11 08:12

Kronos


People also ask

Can I create custom HTTP status code?

You can define custom HTTP response codes (in addition to the standard ones defined by the <HTTP 1.1 specification in RFC #2616>) that the Web Container uses to reply to the users of your Web application in certain cases. This option is available in the web-j2ee-engine. xml descriptor of your Web application.

How can I get status code from Ajax response?

//your jquery code will be like this: $. ajax({ type: 'POST', url: $url, data: new FormData(this), dataType: 'json', contentType: false, processData:false,//this is a must success: function(response){ $('your_selector'). html(response); } }); //php code will be like this echo '<div>some html code</div>'; die();

How do I set HTTP status code in response?

To set a different HTTP status code from your Servlet, call the following method on the HttpServletResponse object passed in to your server: res. setStatus(nnn); where nnn is a valid HTTP status code.

Which series will the HTTP response code belong to in case the server wants to indicate that the client needs to take further action such as go to a new location?

3xx: Redirection. The 3xx status codes indicate that the client needs to do some extra work to get what it wants. They're most commonly used with GET requests, and they usually tell the client that it can only get the representation it wants by sending a second GET request to some other URI.


1 Answers

First things first HttpStatusCode.Unauthorized = 401, not 403 status code. There is an important distinction between those 2 codes.

When you set the status code to 401 some nasty things happen: you automatically get redirected to the Login page by the ASP.NET Forms authentication module => the login page is served with status code = 200. Phil Haack addressed this issue in the following blog post.

As far as throw new HttpException((int)HttpStatusCode.Forbidden, "Forbidden"); is concerned in your controller action, well, you throw an exception that is of type HttpException and whose StatusCode is set to 401 but other than that there is absolutely nothing that will catch this exception and set the corresponding response status code. So the exception bubbles up and since you don't presumably have a global exception handler it is translated as a 500 error page by the server.

Here's an example of a global exception handler that you might find useful.

like image 162
Darin Dimitrov Avatar answered Oct 18 '22 21:10

Darin Dimitrov