【问题标题】:Url delimiter with "-" MVC Routes带有“-”的 URL 分隔符 MVC 路由
【发布时间】:2017-05-03 06:35:26
【问题描述】:

我对 MVC 路由有疑问。 我用过这样的路线:

  [Route("{selected}/{category}/{id}/{engineId}")]
  public ActionResult SubCategories(string selected, int id, string category, string engineId)
    {...}

网址如下所示:http://localhost:50564/Audi-60-1.5/Suspensie/76/43423

但是现在,我需要用“-”分隔 url 参数。我可以这样做吗?我对 MVC 路由没有太多经验,也不知道该怎么做。 如果我把路线改成这样:

[Route("{selected}-{category}-{id}-{engineId}")]
public ActionResult SubCategories(string selected, int id, string category, string engineId)
{...}

我遇到了各种问题,例如整个应用程序中的 Session 变为空,并且我得到空引用异常。使用“/”分隔符我没有这个问题,一切正常。

【问题讨论】:

  • 为什么要这样做?

标签: asp.net-mvc routes


【解决方案1】:

这是一个基本答案,仅包括控制器和动作,但已经过测试并且可以工作。从测试中您也不能包含 - 对于可选参数,您最多可以使用 .您还必须考虑启动应用程序时是否正确读取默认路由

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}-{action=Index}");
        });

这是使用 - 作为可选参数时的错误消息

RoutePatternException: In the segment '{controller=Redaction}-{action=Index}-{id?}', the optional parameter 'id' is preceded by an invalid segment '-'. Only a period (.) can precede an optional parameter.

这是一个示例网址

https://localhost:44365/Home-Index.DocumentId=1

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-06-26
  • 2015-12-26
  • 2014-02-09
  • 2023-03-30
  • 1970-01-01
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多