Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8119535
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T04:49:42+00:00 2026-06-06T04:49:42+00:00

In ASP.NET the FormsAuthenticationModule intercepts any HTTP 401, and returns an HTTP 302 redirection

  • 0

In ASP.NET the FormsAuthenticationModule intercepts any HTTP 401, and returns an HTTP 302 redirection to the login page. This is a pain for AJAX, since you ask for json and get the login page in html, but the status code is HTTP 200.

What is the way of avoid this interception in ASP.NET Web API ?

In ASP.NET MVC4 it is very easy to prevent this interception by ending explicitly the connection:

public class MyMvcAuthFilter:AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && !filterContext.IsChildAction)
        {
            filterContext.Result = new HttpStatusCodeResult(401);
            filterContext.HttpContext.Response.StatusCode = 401;
            filterContext.HttpContext.Response.SuppressContent = true;
            filterContext.HttpContext.Response.End();
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

But in ASP.NET Web API I cannot end the connection explicitly, so even when I use this code the FormsAuthenticationModule intercepts the response and sends a redirection to the login page:

public class MyWebApiAuth: AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if(actionContext.Request.Headers.Any(h=>h.Key.Equals("X-Requested-With",StringComparison.OrdinalIgnoreCase)))
        {
            var xhr = actionContext.Request.Headers.Single(h => h.Key.Equals("X-Requested-With", StringComparison.OrdinalIgnoreCase)).Value.First();

            if (xhr.Equals("XMLHttpRequest", StringComparison.OrdinalIgnoreCase))
            {
                // this does not work either
                //throw new HttpResponseException(HttpStatusCode.Unauthorized);

                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
                return;
            }
        }

        base.HandleUnauthorizedRequest(actionContext);
    }
}

What is the way of avoiding this behaviour in ASP.NET Web API? I have been taking a look, and I could not find a way of do it.

Regards.

PS: I cannot believe that this is 2012 and this issue is still on.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T04:49:43+00:00Added an answer on June 6, 2026 at 4:49 am

    The release notes for MVC 4 RC imply this has been resolved since the Beta – which are you using?

    http://www.asp.net/whitepapers/mvc4-release-notes
    Unauthorized requests handled by ASP.NET Web API return 401 Unauthroized: Unauthorized requests handled by ASP.NET Web API now return a standard 401 Unauthorized response instead of redirecting the user agent to a login form so that the response can be handled by an Ajax client.

    Looking into the source code for MVC there appears to be an functionality added via SuppressFormsAuthRedirectModule.cs

    http://aspnetwebstack.codeplex.com/SourceControl/network/forks/BradWilson/AspNetWebStack/changeset/changes/ae1164a2e339#src%2fSystem.Web.Http.WebHost%2fHttpControllerHandler.cs.

        internal static bool GetEnabled(NameValueCollection appSettings)
        {
                // anything but "false" will return true, which is the default behavior
    

    So it looks this this is enabled by default and RC should fix your issue without any heroics… as a side point it looks like you can disable this new module using AppSettings http://d.hatena.ne.jp/shiba-yan/20120430/1335787815:

    <appSettings> 
        <Add Key = "webapi:EnableSuppressRedirect"  value = "false" /> 
    </appSettings>
    

    Edit (example and clarification)

    I have now created an example for this approach on GitHub. The new redirection suppression requires that you use the two correct “Authorise” attribute’s; MVC Web [System.Web.Mvc.Authorize] and Web API [System.Web.Http.Authorize] in the controllers AND/OR in the global filters Link.

    This example does however draw out a limitation of the approach. It appears that the “authorisation” nodes in the web.config will always take priority over MVC routes e.g. config like this will override your rules and still redirect to login:

    <system.web>
        <authentication mode="Forms">
        </authentication>
        <authorization>
            <deny users="?"/> //will deny anonymous users to all routes including WebApi
        </authorization>
    </system.web> 
    

    Sadly opening this up for some url routes using the Location element doesn’t appear to work and the WebApi calls will continue to be intercepted and redirected to login.

    Solutions

    For MVC applications I am simply suggest removing the config from Web.Config and sticking with Global filters and Attributes in the code.

    If you must use the authorisation nodes in Web.Config for MVC or have a Hybrid ASP.NET and WebApi application then @PilotBob – in the comments below – has found that sub folders and multiple Web.Config’s can be used to have your cake and eat it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

ASP.NET server-side controls postback to their own page. This makes cases where you want
Asp.Net 3.5 / WebForms (no ajax) I am trying to update a delete confirm
ASP.NET MVC 2 will support validation based on DataAnnotation attributes like this: public class
ASP.NET AJAX 4 recently added the ability to track changes to ADO.NET Data Services
[ASP .Net - Microsoft Visual Web Developer 2010] Hi all, I've problem with this
ASP .NET MVC2 application controller performs some action and redirects to grid page after
ASP.NET Ajax Library provides some client-side events. For instance: Sys.Application.add_load( function(args) { // handle
ASP.NET newbie here. When on a page I'd like to set the corresponding menu
ASP.Net MVC 3. I found similar questions/answers, but none seem to fix this issue...
Asp.net team had designed script manager such that only one instance existed per page(HttpHandler),

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.