【问题标题】:Redirection is not performed because of Ajax call由于 Ajax 调用,未执行重定向
【发布时间】:2017-08-24 13:36:53
【问题描述】:

我有一个简单的登录表单,在登录按钮上单击它会在AccountController 中执行对ActionResult LogIn(LogInRequest request) 的ajax 调用,返回JsonResult。我有CustomHandleErrorAtribute,它继承自HandleErrorAttribute 并重定向到CustomErrorPage.cshtml。 ActionResult 中的某个地方抛出异常,应该由CustomHandleErrorAtribute 处理并处理。然后执行 CustomErrorPage 操作,但实际上并没有返回视图。它停留在同一个 LogInPage 上。

我在 AccountsController 中的登录操作

[AllowAnonymous]
[HttpPost]
[CustomAttributes.CustomHandleError]
public ActionResult Login(LogInRequest request)
{
    StandartResponse finalResult = new StandartResponse();
    //some code that trows exception
    return new JsonResult() { Data = finalResult.Result};
}

点击登录按钮时我的 Ajax 调用:

function LogInUser(s, e) {
var example = { username: UserName.GetValue(), password: Password.GetValue() };
$.ajax({
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    type: "POST",
    url: "/Account/LogIn",
    data: JSON.stringify({ request: example }),
    success: function (data) {

        jQuery.ajaxSettings.traditional = true;
        if (data.Status == InfoType.Success) {
            alert('success');
            var url = "/Home/Index";
            window.location.href = url;
        }
        else {
            alert('here');
            var result = JSON.stringify(data.Infoes);
            popUpErrorMessagePartial.PerformCallback({ message: result });
            popUpErrorMessagePartial.Show();
        }
    },
    error: function(){
       alert('error');
    }
   });
}

CustomHandleErrorAttribute:

public override void OnException(ExceptionContext filterContext)
{


        filterContext.ExceptionHandled = true;
        filterContext.Result =
        new RedirectToRouteResult(new RouteValueDictionary
               {
                   { "action", "ErrorUnauthorised" },
                   { "controller", "CustomErrorPages" },
                   { "Area", String.Empty }
               });
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 500;

}

调试CustomErrorPage的Action后,执行了ajax调用中的错误,显示alert,不做重定向。你知道怎么处理吗?

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    因为您确实遇到了异常,所以 ajax 调用本身会失败,这就是您收到警报的原因,但您无法重定向到 ajax 调用的服务器端内的另一个页面。相反,您可以将重定向放在 ajax 调用的失败块中。有点像....

    error: function(){
       window.location = <put error page url here>
       alert('error');
    }
    

    【讨论】:

    • 谢谢,我会将您的回复标记为答案。对于那些在这方面苦苦挣扎的人,我在这里找到了可能的解决方案,使用 CustomAjaxHandleErrorAtribute 将 Json 结果返回给 ajax 调用的错误函数:stackoverflow.com/questions/9298466/…
    猜你喜欢
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 2013-12-03
    相关资源
    最近更新 更多