title: In Asp.Net MVC 2 is there a better way to return 401 status codes without getting an auth redirect
body: <p>I have a portion of my site that has a lightweight xml/json REST API.  Most of my site is behind forms auth but only some of my API actions require authentication.</p>
  
  <p>I have a custom AuthorizeAttribute for my API that I use to check for certain permissions and when it fails it results in a 401.  All is good, except since I'm using forms auth, Asp.net conveniently converts that into a 302 redirect to my login page.  </p>
  
  <p><strong>I've seen some previous questions</strong> that seem a bit hackish to either return a 403 instead or to put some logic in the global.asax  <strong>protected void Application_EndRequest()</strong>
  that will essentially convert 302 to 401 where it meets whatever criteria.</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/123726/401-response-code-for-json-requests-with-asp-net-mvc">Previous Question</a></li>
  <li><a href="https://stackoverflow.com/questions/2580596/how-do-you-handle-ajax-requests-when-user-is-not-authenticated/2595436#2595436">Previous Question 2</a></li>
  </ul>
  
  <p>What I'm doing now is sort of like one of the questions, but instead of checking the <strong>Application_EndRequest()</strong> for a 302 I make my authorize attribute return <strong>666</strong> which indicates to me that I need to set this to a 401.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>protected void Application_EndRequest()
  {
    if (Context.Response.StatusCode == MyAuthAttribute.AUTHORIZATION_FAILED_STATUS)
     {   
         //check for 666 - status code of hidden 401
          Context.Response.StatusCode = 401;
      }
   }
  </code></pre>
  
  <p>Even though this works, <strong>my question is there something in Asp.net MVC 2 that would prevent me from having to do this?  Or, in general is there a better way?</strong>  I would think this would come up a lot for anyone doing REST api's or just people that do ajax requests in their controllers.  The last thing you want is to do a request and get the content of a login page instead of json.</p>