在ASP.NET MVC 5中路由可选参数

Fel*_*ani 28 c# asp.net asp.net-mvc routing asp.net-mvc-5

我正在创建一个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...
}
Run Code Online (Sandbox Code Playgroud)

如果我们/在最后传递斜杠char ,我们只能访问此URL url,如下所示:

type/lib/version/file/cache/
Run Code Online (Sandbox Code Playgroud)

它工作正常但没有工作/,我得到一个404未找到的错误,像这样

type/lib/version/file/cache
Run Code Online (Sandbox Code Playgroud)

或者这个(没有可选参数):

type/lib/version
Run Code Online (Sandbox Code Playgroud)

我希望/在结尾处使用或不使用char url.我的最后两个参数是可选的.

RouteConfig.cs是这样的:

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

        routes.MapMvcAttributeRoutes();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Ohl*_*lin 37

也许你应该尝试将你的枚举作为整数?

这就是我做到的

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的路由文件

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 });
}
Run Code Online (Sandbox Code Playgroud)

然后,我可以拨打电话

http://localhost:52392/2/lib1/ver1/file1/1
http://localhost:52392/2/lib1/ver1/file1
http://localhost:52392/2/lib1/ver1
Run Code Online (Sandbox Code Playgroud)

要么

http://localhost:52392/2/lib1/ver1/file1/1/
http://localhost:52392/2/lib1/ver1/file1/
http://localhost:52392/2/lib1/ver1/
Run Code Online (Sandbox Code Playgroud)

它工作正常......