gpt4 book ai didi

javascript - 在 ajax 方法中调用 filterContext.Result 时如何重定向页面?

转载 作者:行者123 更新时间:2023-11-29 16:50:05 28 4
gpt4 key购买 nike

我遇到了一个我不知道如何解决的问题。

我的问题的上下文是基于需要在 session 变量丢失时将用户重定向到登录。

我们正在做的是对 Controller Action 进行装饰,预览以执行 Action ,验证名为 ["SesionesPorUsuarios"] 的 session 变量不同于 null

像这样:

    [HttpPost]
[IndicadorUltimaAccionDelSistema()]
public JsonResult ConsulteLosProductos(string elAliasDelTipoDeProducto)
{
//stuffs...
}

然后像这样:

    public class IndicadorUltimaAccionDelSistema : ActionFilterAttribute
{

/stuffs...
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session["SesionesPorUsuarios"] != null)
{
/stuffs...
}
else
{
/stuffs...
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "Login" },
{ "controller", "Login" }
});
}
}
}

我们的登录操作是:

public ActionResult Login()
{
return View();
}

当在 $.post() 之类的 ajax 方法中调用操作时,我们遇到了问题

post 方法获取操作“登录”返回的所有 View ,但它不会将用户重定向到登录页面,post 方法获取操作“登录”返回的所有 html,并将其视为JSON 对象。

enter image description here

任何人都知道我们如何解决这个问题,或者我们可以申请什么解决方法

谢谢...

最佳答案

您将必须检查它是否是一个 ajax 请求并将 url 作为 json 发送,并在客户端检查该参数是否存在通过 js 从客户端重定向:

if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.Result = new JsonResult { Data = "LogOut"};
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "Login" },
{ "controller", "Login" }
});
}

并注册 ajaxError 事件并在其中检查值和重定向:

   $(document).ajaxError(function(e, xhr, opts) {

if (xhr.status == 403 && xhr.responseText.indexOf("LogOut") != -1) {
window.location.href = "@Url.Action("Login", "Account")";
}

});

现在在任何 ajax 调用中,如果 session 为空,用户将被重定向到登录操作。

你也可以返回一个对象而不是字符串,就像@Shyju 在帖子中演示的那样,我使用字符串来保持简单:)

关于javascript - 在 ajax 方法中调用 filterContext.Result 时如何重定向页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36870613/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com