首页 > 解决方案 > 如何检查“非前缀”

问题描述

这是我的RegisterRoutes内心RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Worktypes",
        url: "Clinic/Worktypes/{action}/{id}",
        defaults: new { controller = "Worktypes", action = "Index", id = UrlParameter.Optional }
    );

    // default (finance)
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

哪个有效,访问/Clinic/Worktypes. 问题是,如果我/Worktypes在 url 中输入数字,它也可以工作。如何防止访问“非前缀”控制器?

标签: .netasp.net-mvc

解决方案


我不认为这是最优雅的解决方案,也许有更好的解决方案。

但是,我在我的一个项目中遇到了类似的问题,我通过使用命名空间约束来解决。

因此,在您的路由注册中,前提是您的前缀控制器具有与需要转到默认路由的其余控制器不同的命名空间

var route = routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    // lets assume that your non prefixed controllers are under the WebApp.Controllers
    // namespace
    namespaces: new []{ "WebApp.Controllers" }
);

// note, this is an important part. Basically you tell this route to match only the 
// controller that are under that namespace, specified in the route
route.DataTokens["UseNamespaceFallback"] = false;

希望这可以帮助


推荐阅读