asp.net mvc路由约束正则表达式

asp.net mvc route constraints regular expression

我想使用 url 服务器动态页面,没有基于页面标题的控制器和操作
默认 url : domain.com/pages/details/1
我希望它成为服务器
domain.com/title-of-dynamic-page-in-db-space-replaced-with-dash
domain.com/about-us
domain.com/contact-us

如果我在没有破折号的情况下执行此操作,那么路由会与 controller 名称
混淆 这就是为什么我为动态页面添加破折号 -

我的动作是这样的

    // GET: Pages/View/5
    public ActionResult View(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Page page = db.Pages.First(p => p.name_english == id.Replace("-"," "));
        if (page == null)
        {
            return HttpNotFound();
        }
    }

我的路线是

        routes.MapRoute(
            name: "aaaaa",
            url: "{id}",
            defaults: new { controller = "pages", action = "view" },
            constraints: new { id = @"^[A-Za-z\d-]+$" } //*********help needed in this line ******************************
        );


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

以上约束^[A-Za-z\d-]+$
接受 alpha(optional) numeric(optional)dash(optional)

而我需要 alpha(optional) numeric(optional)dash(*mandatory*)

这样路由引擎不会将页面标题与 controller/action 混淆,因为我将确保我的动态页面名称将包含 space(我将替换为破折号)
我的 controller/action 不会被命名为包含破折号

也告诉我,这个方法好不好,有没有其他优化的方案?

希望以下代码段对您有用。

    routes.MapRoute(
        name: "aaaaa",
        url: "{id}",
        defaults: new { controller = "pages", action = "view" },
        constraints: new { id = @"^([-]*[a-zA-Z0-9]*-[a-zA-Z0-9]*[-]*)+$" } //*********this should work**
    );

    //---------------------------------------
    // ^([-]*[a-zA-Z0-9]*-[a-zA-Z0-9]*[-]*)+$
    //---------------------------------------