0

Using asp.net MVC 5... A controller with an ActionResult is providing Json for an ajax call.

Under certain conditions, I want to return an response StatusCode of 401 (unauthorized) or 500.

When I do any of the following error results, the entire home Index page is returned instead:

 public ActionResult _VideoPlayerJson(int? id){
  ...

    Response.TrySkipIisCustomErrors = true; //has no effect
    //Any of the following will result in the entire Index page being returned to the caller.

    if (bad){return new HttpStatusCodeResult(HttpStatusCode.Unauthorized, "You must be logged in")};

    if (bad2){ throw new HttpException((int)HttpStatusCode.Unauthorized, "You must be logged in");}

    if (bad3) {
         Response.Statuscode = 401;
         return Json(new {error="some error"}, JsonRequestBehavior.AllowGet);
    }

    if (ok) {
         //This is OK, and returns as expected
         return Json(new {someobject=bob}, JsonRequestBehavior.AllowGet);
    }
...}

If I put a break on the Index controller, I can see see that some hidden-under-the-hood Asp.NET mysterious mechanism has redirected the result to the Index page and set the request ReturnURL to the original url.

I can't figure out what's causing this, or how to defeat it. I really hate the mysteries Microsoft tries to help us with sometimes.

NOTE: In Global.asax.cs...

  • Application_Error never gets called (via the above calls)
  • Application_PreRequestHandlerExecute is called 2x. Once before my controller method above, and once after I set the error statatus, and before the Home/Index controller is called

ALSO: The call stack at Application_AuthenticateRequest (during the redirect) starts with some internal function: System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification (not very helpful)

user910531
  • 89
  • 1
  • 7
  • See [Why does AuthorizeAttribute redirect to the login page for authentication and authorization failures?](http://stackoverflow.com/a/5844884/181087) – NightOwl888 May 31 '16 at 21:43

1 Answers1

1

OK... just avoid using 401, and everything is fine. Using Forbidden (403) produces the desired results without the redirect.

For some reason ASP.NET MVC redirects all 401's to home.... which is really annoying when you are trying to return JSON to an ajax call...

user910531
  • 89
  • 1
  • 7
  • See here for a great article:http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx/ – user910531 May 31 '16 at 21:41