重定向到页面 OnActionExecuting 方法 ASP.NET Core 5 MVC

Adn*_*nan 5 c# asp.net-core-mvc .net-core asp.net-core .net-5

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

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" }
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Kin*_*ing 4

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

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

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" }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

注意GoToLogin您的代码中的 不清楚,如果您的意思是您不知道它的条件(以防止重定向循环),只需将其设置如下:

var goToLogin = !Equals(controller.TempData["__redirected"], true);
Run Code Online (Sandbox Code Playgroud)

或者不改变它的值:

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

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