且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-06 22:12:48

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

Maybe you should try to have your enums as integers instead?

我就是这样做的

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 });
}

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

I can then make calls like

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/

它工作正常......

and it works fine...