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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19795198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:36:45  来源:igfitidea点击:

Server side redirection after jquery ajax call in asp.net mvc 4

jqueryajaxasp.net-mvc-4

提问by s.k.paul

I am sending login information from a jQuery AJAX call to an MVC 4 controller:

我正在从 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");
      }
   });

If the login is successful, I want to redirect a user from the server-side to the appropriate page on the basis of user type. If the login fails, a string is sent back to user:

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

    [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.
        }
    }

But there are problems:

但是存在以下问题:

  1. If this method returns 'ActionResult', then I'm getting the error not all code paths return a value.

  2. If I use 'void', I cannot return anything.

  3. Even if I use 'void' with no return, I am failing to redirect to other controller or view due to asynchronous nature of jQuery AJAX calls.

  1. 如果此方法返回“ActionResult”,则我收到错误not all code paths return a value

  2. 如果我使用“void”,则无法返回任何内容。

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

Are there any techniques to handle such scenarios?

有什么技术可以处理这种情况吗?

回答by Ramunas

returnusually returns from method without executing any further statements in it so elsepart is not needed. This way you will get rid of a problem #1.

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

As for redirecting why not return some kind of redirectcommand:

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

[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")});
}

And then in javascript:

然后在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;
  }
 });

回答by BJ Patel

This help me.

这对我有帮助。

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

Ref. link How to get an ASP.NET MVC Ajax response to redirect to new page...

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

回答by Shahin Dohan

I had to do this but none of the solutions I found really satisfied my extreme requirements of JavaScript parsing errors that I had to avoid in order to redirect the client to the login page.

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

What I did was to send a simple "NOAUTH" string response from my custom Authorization attribute, then intercept the Ajax response before any event handlers are hit, and redirect the user by setting window.location.

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

Server side:

服务器端:

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

Then on the client side:

然后在客户端:

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

I would not recommend this approach though. If you have to do this, then I would at-least suggest instead putting the "NOAUTH" value inside the http response header, then read the value in a global JQuery complete handler.

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

Server side:

服务器端:

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

Client-side:

客户端:

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

Note that using dataFilter is the onlyway to intercept ajax requests before any other of your event handlers are hit.

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