<p>How to disable standard ASP.NET handling of 401 response code (redirecting to login page) for AJAX/JSON requests?</p>

<p>For web-pages it's okay, but for AJAX I need to get right 401 error code instead of good looking 302/200 for login page.</p>

<p><strong>Update</strong>:
There are several solutions from Phil Haack, PM of ASP.NET MVC - <a href="http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx" rel="noreferrer">http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx</a></p>

You could choose to create a custom
```
FilterAttribute
```
implementing the
```
IAuthorizationFilter
```
interface.
In this attribute you add logic to determine if the request are supposed to return JSON. If so, you can return an empty JSON result (or do whatever you like) given the user isn't signed in. For other responses you would just redirect the user as always.
Even better, you could just override the
```
OnAuthorization
```
of the
```
AuthorizeAttribute
```
class so you don't have to reinvent the wheel. Add the logic I mentioned above and intercept if the
```
filterContext.Cancel
```
is true (the
```
filterContext.Result
```
will be set to an instance of the
```
HttpUnauthorizedResult
```
class.
Read more about
"Filters in ASP.NET MVC CodePlex Preview 4"
on Phil Haacks blog. It also applies to the latest preview.