【发布时间】:2016-06-01 07:30:39
【问题描述】:
使用 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);
}
...}
如果我在 Index 控制器上打断,我可以看到一些隐藏在引擎盖下的 Asp.NET 神秘机制已将结果重定向到 Index 页面并设置请求ReturnURL 到原来的 url。
我不知道是什么原因造成的,也不知道如何解决。我真的很讨厌微软有时试图帮助我们解决的谜团。
注意:在 Global.asax.cs...
- Application_Error 永远不会被调用(通过上述调用)
- Application_PreRequestHandlerExecute 被称为 2x。一次在我上面的控制器方法之前,一次在我设置错误状态之后,在调用 Home/Index 控制器之前
也: Application_AuthenticateRequest 的调用堆栈(在重定向期间)从一些内部函数开始:System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification (不是很有帮助)
【问题讨论】:
标签: asp.net asp.net-mvc redirect asp.net-mvc-5