在asp.net mvc 4中调用jquery ajax之后的服务器端重定向

我将jQuery AJAX调用的登录信息发送到MVC 4控制器:

$.post(url, data, function (response) { if (response=='InvalidLogin') { //show invalid login } else if (response == 'Error') { //show error } else { //redirecting to main page from here for the time being. window.location.replace("http://localhost:1378/Dashboard/Index"); } }); 

如果登录成功,我想根据用户类型将用户从服务器端重定向到适当的页面。 如果登录失败,则会将一个字符串发送回用户:

  [HttpPost] public ActionResult Index(LoginModel loginData) { if (login fails) { return Json("InvalidLogin", JsonRequestBehavior.AllowGet); } else { // I want to redirect to another controller, view, or action depending // on user type. } } 

但是有一些问题:

  1. 如果此方法返回’ActionResult’,那么我收到错误not all code paths return a value

  2. 如果我使用’void’,我就无法返回任何内容。

  3. 即使我使用’void’而没有返回,由于jQuery AJAX调用的异步性,我无法重定向到其他控制器或视图。

有没有技术来处理这种情况?

return通常从方法返回而不执行任何进一步的语句,所以不需要部分。 这样你就可以解决问题#1。

至于重定向,为什么不返回某种重定向命令:

 [HttpPost] public ActionResult Index(LoginModel loginData) { if (login fails) { return Json(new {result = "InvalidLogin"}, JsonRequestBehavior.AllowGet); } return Json(new {result = "Redirect", url = Url.Action("MyAction", "MyController")}); } 

然后在javascript中:

 $.post(url, data, function (response) { if (response.result == 'InvalidLogin') { //show invalid login } else if (response.result == 'Error') { //show error } else if (response.result == 'Redirect'){ //redirecting to main page from here for the time being. window.location = response.url; } }); 

这对我有帮助。

 return JavaScript("window.location = '/'"); 

参考。 链接如何获取ASP.NET MVC Ajax响应以重定向到新页面…

我不得不这样做,但我发现的解决方案都没有满足我对JavaScript解析错误的极端要求,为了将客户端重定向到登录页面,我必须避免这些错误。

我所做的是从我的自定义Authorization属性发送一个简单的“NOAUTH”字符串响应,然后在任何事件处理程序被命中之前拦截Ajax响应,并通过设置window.location来重定向用户。

服务器端:

 protected override void HandleUnauthorizedRequest(AuthorizationContext context) { if (context.RequestContext.HttpContext.Request.IsAjaxRequest()) { var result = new ContentResult {Content = "NOAUTH"}; context.Result = result; return; } } 

然后在客户端:

 $.ajaxSetup({ dataFilter: function (data, type) { if (data !== "" && data === "NOAUTH") { window.location = '/'; } return data; } }); 

我不会推荐这种方法。 如果你必须这样做,那么我至少建议将“NOAUTH”值放在http响应头中,然后在全局JQuery完整处理程序中读取值。

服务器端:

 HttpContext.Current.Response.AddHeader("NOAUTH", "1"); 

客户端:

 $.ajaxSetup({ complete: function (jqXHR, textStatus) { if (jqXHR.getResponseHeader("NOAUTH") === '1') window.location = '/'; } }); 

请注意,使用dataFilter是在任何其他事件处理程序被命中之前拦截ajax请求的唯一方法。