【问题标题】:asp.net mvc route constraints regular expressionasp.net mvc 路由约束正则表达式
【发布时间】:2019-02-10 13:50:07
【问题描述】:

我想根据页面标题使用不带控制器和操作的 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*)

这种方式路由引擎不会将页面标题与控制器/动作混淆,因为我将确保我的动态页面名称将包含空格(我将替换为破折号)
并且我的控制器/动作不会被命名为包含破折号

也告诉我,这种方法是否可行,是否有其他优化解决方案?

【问题讨论】:

  • ^([a-zA-Z0-9]+-[a-zA-Z0-9]+)+$
  • 你这行得通:),这种方法可以吗,还是有其他最好的解决方案?
  • 没关系。您需要使用路由约束来满足您的要求。
  • @FakhrAlam 你确定^([a-zA-Z0-9]+-[a-zA-Z0-9]+)+$ 适合你吗?你说你需要alpha(optional)numeric(optional)和dash(*mandatory*),但是上面的模式在开始时需要alpha字符。请让您的问题更清楚。
  • 你是对的@Wilktor,开头和结尾的hypen 不起作用。请更正此 reg exp

标签: regex asp.net-mvc-5 asp.net-mvc-routing dynamic-pages


【解决方案1】:

我希望下面的 sn-p 对你有用。

    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]*[-]*)+$
    //---------------------------------------

【讨论】:

    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多