Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect unauthorize Ajax reqest on Controller to login page? .

[Authorize]
public class MyController : BaseController
{
    [PermissionAuthorize]
    public ActionResult GridData()
    {
        return Json(data, JsonRequestBehavior.AllowGet);
    }
}

I have Created PermissionAuthoize attribute for check permission of user on particular action. I have a problem After the User session or ticket is expire at that time if user send ajax requrest to Controller then Authorize attribute reject the request and return as html login form to user.this region user think app is not performing. its show the bad impact to user.

so , i want to redirect to user to login page if they send ajax request on ticket expire.

Can i create one other authorize attribute for controller is it gud way?

like image 563
pargan Avatar asked Mar 14 '13 07:03

pargan


People also ask

Can you redirect an ajax request?

Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url. Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.

How do I redirect a page in ajax?

ajax({ type: 'POST', url: 'b. php', data: 'result='+$name, success: function() { window. location. href = "profile.

How redirect ajax in php?

If you want to do a full redirect, you can use window. location = 'addcust. php? new_sale='+youridvariable In the success callback.


1 Answers

The first thing you need to do is to configure the forms authentication module to stop redirecting to the logon page when 401 is thrown. Phil Haack wrote a nice article about how this could be achieved.

Once you do that you will be able to capture 401 HTTP status codes on the client. So you could write a global ajax handler that will redirect to the logon page when 401 status code is sent from the server (which will happen when the forms authentication ticket expires or the user is not authenticated at all):

$(document).ajaxError(function(event, jqxhr, settings, exception) {
    if (jqxhr.status == 401) {
        // unauthorized
        window.location.href = '/logon';
    }
});
like image 50
Darin Dimitrov Avatar answered Oct 06 '22 00:10

Darin Dimitrov