Saravanan
Saravanan

Reputation: 7854

Handling the Request redirects in ASP.Net MVC 2 with ajax requests

I have developed an ASP.NET MVC2 application and in that i have a login feature implemented.

I have other views that have ajax calls. At times, i find the ajax calls displaying the login page.

In an attempt to get rid of this problem, i have tried to simulate the situation, but the response code that i get from my application was 200 which is OK

I am using ASP.Net MVC2. Why am i getting 200, where i should be actually getting a 302 server redirect for login page redirection from my current view.

Guide me to handle this situation.

Upvotes: 0

Views: 255

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

Why am i getting 200, where i should be actually getting a 302 server redirect for login page redirection from my current view.

It's because jQuery follows the redirect and you end up with 200 and the login page. I would recommend you the following article which illustrates a very elegant way to configure ASP.NET to send 401 status code for unauthenticated requests assuming this request was made using an AJAX call. Then your client code will look like this:

$.ajax({
    url: '/foo',
    type: 'POST',
    data: { foo: 'bar' },
    statusCode: {
        200: function (data) {
            alert('200: Authenticated');
            // Do whatever you was intending to do
            // in case of success
        },
        401: function (data) {
            alert('401: Unauthenticated');
            // Handle the 401 error here. You can redirect to 
            // the login page using window.location.href
        }
    }
});

Upvotes: 1

Related Questions