The result of your AJAX call will still seem successful (although, donβt worry, it will not actually execute your action method) and call the success handler. This is because you expect HTML, and that is what you get (although most likely your HTML code is most likely your login page, not the HTML you wanted). As an aside, if you were expecting JSON (using dataType:'JSON' ), it would dataType:'JSON' an error because it would be parsing HTML as JSON.
What you need to do is prevent FormsAuth from redirecting the login page for AJAX requests. AuthorizeAttribute now correctly returns NotAuthorizedResult , which sends an HTTP 401 HTTP autoresponder to the client, which is ideal for your AJAX client.
The problem is that the FormsAuth module checks the StatusCode and, if it is 401, it redirects. I solved this problem this way:
1) Create your own derived type, AuthorizeAttribute , which puts the flag in HttpContext.Items to let me know that authorization has failed and I must force 401, not a redirect:
public class AjaxAuthorizeAttribute : AuthorizeAttribute {
2) Add to your Global.asax.cs file:
protected void Application_EndRequest(Object sender, EventArgs e) { if (Context.Items["AjaxPermissionDenied"] is bool) { Context.Response.StatusCode = 401; Context.Response.End(); } }
3) Add a statusCode handler to your jQuery AJAX setup:
$.ajaxSetup({ statusCode: { 401: function() { window.location.href = "path/to/login"; } } });
4) Change the controllers or actions in which you want this behavior to use AuthorizeAttribute - AjaxAuthorizeAttribute :
[AjaxAuthorize] public string SaveEmployee(string Location, string dateApplied, string Status, string mailCheck, ...) { objEmpMain.FirstName = firstName; objEmpMain.LastName = lastName; objEmpMain.Initial = Initial; objEmpMain.Address1 = Address; ... ... ... }