Redirect with RedirectToRouteResult does not work

2020-05-25 06:32发布

问题:

I have this ActionFilter

public class AppOfflineFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionDescriptor.ActionName != "AppOffLine" &&
            filterContext.HttpContext.Request.UserHostName != "127.0.0.1")
        {
            filterContext.Result = new RedirectToRouteResult(
                 new RouteValueDictionary(
                     new  { action = "AppOffLine", Controller = "Home" }));
        }
    }
}

It works from the start page which is does not reside under a Area, it does not work from an area because it will redirect to /Area/Home/Appoffline instead of /Home/AppOffline

Can it be fixed?

Also is there a way of speciefing which controller / action to redirect to using Generics and strongly typed code?

回答1:

Try assigning the area route token to an empty string:

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { 
    action = "AppOffLine", 
    controller = "Home", 
    area = "" 
}));


回答2:

you must specify area like this:

public class AppOfflineFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionDescriptor.ActionName != "AppOffLine" &&
            filterContext.HttpContext.Request.UserHostName != "127.0.0.1")
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new { action = "AppOffLine", Controller = "Home",
                          area = "YourAreaName" })); //<<<<THIS
        }
    }
}

and if you want to redirect to a non-area zone (like /Home/Index), set 'area' to an empty string; like:

area=""