【问题标题】:Routing optional parameters in ASP.NET MVC 5ASP.NET MVC 5 中的路由可选参数
【发布时间】:2026-01-01 11:55:01
【问题描述】:

我正在创建一个 ASP.NET MVC 5 应用程序,但我遇到了一些路由问题。我们正在使用属性Route 在 Web 应用程序中映射我们的路线。我有以下操作:

[Route("{type}/{library}/{version}/{file?}/{renew?}")]
public ActionResult Index(EFileType type, 
                          string library, 
                          string version, 
                          string file = null, 
                          ECacheType renew = ECacheType.cache)
{
 // code...
}

如果我们在url 的末尾传递斜线字符/,我们只能访问此URL,如下所示:

type/lib/version/file/cache/

它工作正常,但没有/ 就无法工作,我得到一个404 not found 错误,像这样

type/lib/version/file/cache

或者这个(不带可选参数):

type/lib/version

我想在url 末尾使用或不使用/ 字符访问。我的最后两个参数是可选的。

我的RouteConfig.cs是这样的:

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

        routes.MapMvcAttributeRoutes();
    }
}

我该如何解决?让斜线/ 也是可选的吗?

【问题讨论】:

  • “不起作用”是指您得到 404 Not Found?
  • 是的! 404错误,如果我添加一个断点,它只是没有命中断点!
  • 应用程序是否托管为虚拟目录?
  • 从 Visual Studio 开始,在 IIS Express 上运行!
  • 如果没有提供{file},但提供了{renew},它怎么知道你提供了哪一个,因为它们都是可选的?

标签: c# asp.net asp.net-mvc routing asp.net-mvc-5


【解决方案1】:

也许您应该尝试将枚举改为整数?

我就是这样做的

public enum ECacheType
{
    cache=1, none=2
}

public enum EFileType 
{
    t1=1, t2=2
}

public class TestController
{
    [Route("{type}/{library}/{version}/{file?}/{renew?}")]
    public ActionResult Index2(EFileType type,
                              string library,
                              string version,
                              string file = null,
                              ECacheType renew = ECacheType.cache)
    {
        return View("Index");
    }
}

还有我的路由文件

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

    // To enable route attribute in controllers
    routes.MapMvcAttributeRoutes();

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

然后我可以像这样拨打电话

http://localhost:52392/2/lib1/ver1/file1/1
http://localhost:52392/2/lib1/ver1/file1
http://localhost:52392/2/lib1/ver1

http://localhost:52392/2/lib1/ver1/file1/1/
http://localhost:52392/2/lib1/ver1/file1/
http://localhost:52392/2/lib1/ver1/

而且效果很好……

【讨论】:

    【解决方案2】:
    //its working with mvc5
    [Route("Projects/{Id}/{Title}")]
    public ActionResult Index(long Id, string Title)
    {
        return view();
    }
    

    【讨论】: