ASP.NET MVC ActionResult中的HttpStatusCodeResult()导致返回索引

时间:2016-05-31 21:26:10

标签: asp.net asp.net-mvc redirect asp.net-mvc-5

使用asp.net MVC 5 ... 带有ActionResult的控制器正在为ajax调用提供Json。

在某些情况下,我想返回一个401(未授权)或500的响应StatusCode。

当我执行以下任何错误结果时,将返回整个主页索引页面:

 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);
    }
...}

如果我在索引控制器上休息一下,我可以看到一些隐藏在幕后的Asp.NET神秘机制已将结果重定向到索引页面并设置请求returnURL到原始网址。

我无法弄清楚造成这种情况的原因,或者如何打败它。我真的很讨厌微软有时试图帮助我们的奥秘。

注意:在Global.asax.cs中......

  • 永远不会调用Application_Error(通过上述调用)
  • Application_PreRequestHandlerExecute被称为2x。一次在我的控制器方法之前,一次在我设置错误statatus之后,在调用Home / Index控制器之前

同时: Application_AuthenticateRequest中的调用堆栈(在重定向期间)以一些内部函数启动:System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification (不是很有帮助)

1 个答案:

答案 0 :(得分:1)

好的......只是避免使用401,一切都很好。 使用Forbidden(403)可以在没有重定向的情况下生成所需的结果。

出于某种原因,ASP.NET MVC将所有401重定向到home ....当你试图将JSON返回到ajax调用时,这真的很烦人......

相关问题