如何在执行重定向之前确保控制器和操作存在,asp.net mvc3

2023-11-23

在我的控制器+操作对之一中,我从某处以字符串形式获取另一个控制器和操作的值,并且我想重定向当前操作。在进行重定向之前,我想确保我的应用程序中存在控制器+操作,如果不存在,则重定向到 404。我正在寻找一种方法来执行此操作。

public ActionResult MyTestAction()
{
    string controller = getFromSomewhere();
    string action = getFromSomewhereToo();

    /*
      At this point use reflection and make sure action and controller exists
      else redirect to error 404
    */ 

    return RedirectToRoute(new { action = action, controller = controller });
}

我所做的就是这个,但它不起作用。

var cont = Assembly.GetExecutingAssembly().GetType(controller);
if (cont != null && cont.GetMethod(action) != null)
{ 
    // controller and action pair is valid
}
else
{ 
    // controller and action pair is invalid
}

你可以实施IRouteConstraint并在您的路由表中使用它。

该路由约束的实现可以使用反射来检查控制器/操作是否存在。如果不存在,则将跳过该路线。作为路由表中的最后一条路由,您可以设置一个捕获所有路由并将其映射到呈现 404 视图的操作。

这里有一些代码片段可以帮助您开始:

public class MyRouteConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {

            var action = values["action"] as string;
            var controller = values["controller"] as string;

            var controllerFullName = string.Format("MvcApplication1.Controllers.{0}Controller", controller);

            var cont = Assembly.GetExecutingAssembly().GetType(controllerFullName);

            return cont != null && cont.GetMethod(action) != null;
        }
    }

请注意,您需要使用控制器的完全限定名称。

路由配置.cs

routes.MapRoute(
                "Home", // Route name
                "{controller}/{action}", // URL with parameters
                new { controller = "Home", action = "Index" }, // Parameter defaults
                new { action = new MyRouteConstraint() } //Route constraints
            );

routes.MapRoute(
                "PageNotFound", // Route name
                "{*catchall}", // URL with parameters
                new { controller = "Home", action = "PageNotFound" } // Parameter defaults
            );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在执行重定向之前确保控制器和操作存在,asp.net mvc3 的相关文章

随机推荐