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)