【问题标题】:Redirect to page OnActionExecuting method ASP.NET Core 5 MVC重定向到页面 OnActionExecuting 方法 ASP.NET Core 5 MVC
【发布时间】:2021-03-21 20:51:45
【问题描述】:

我有一个问题,请求重定向太多次,我只想转到新的重定向路由,那么我该如何防止这种情况发生,或者有什么我不知道的?

public class AuthController : Controller
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (GoToLogin)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                { "controller", "account" },
                { "action", "login" }
            });
        }
    }
}

【问题讨论】:

    标签: c# asp.net-core .net-core asp.net-core-mvc .net-5


    【解决方案1】:

    重定向的循环相当清晰。您的重定向请求必须是可识别的,以便您的代码可以检查并且不对该重定向请求执行重定向(因此不会执行循环并导致过多重定向错误)。

    您的代码可以像这样简单:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        //obtain the controller instance
        var controller = context.Controller as Controller;
    
        //not sure where you define the GoToLogin here, I assume it's available as a bool
        GoToLogin &= !Equals(controller.TempData["__redirected"], true);
        if (GoToLogin)
        {
            //set a temp data value to help identify this kind of redirected request
            //which will be later sent by the client.
            //The temp data value will be deleted the next time read (the code above)
            controller.TempData["__redirected"] = true;
    
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                { "controller", "account" },
                { "action", "login" }
            });
        }
    }
    

    注意:您的代码中的GoToLogin 不清楚,如果您的意思是您不知道它的条件是什么(以防止重定向循环) ,只要这样设置:

    var goToLogin = !Equals(controller.TempData["__redirected"], true);
    

    或者不改变它的值:

    if (GoToLogin && !Equals(controller.TempData["__redirected"], true)){
       //redirect the request ...
    }
    

    在这里使用TempData 的好处是可以在第一次阅读后自动删除。所以在接收到重定向请求的时候,TempData中包含的值为true,使得整个GoToLoginfalse(或者不满足重定向的条件),重定向将不会进行。之后,TempData 中包含的值将被清除(删除)并为下一次重定向做好准备。

    【讨论】:

      【解决方案2】:

      试试这个:

      filterContext.Result = new RedirectToActionResult ("<Action>", "<Controller>", null);
      base.OnActionExecuting(filterContext);
      

      【讨论】:

      • 同样的事情。
      猜你喜欢
      • 2021-09-27
      • 2015-02-09
      • 2013-03-11
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 2020-09-06
      相关资源
      最近更新 更多