Routing optional parameters in ASP.NET MVC 5

后端 未结 2 561
孤独总比滥情好
孤独总比滥情好 2020-12-03 06:31

I am creating an ASP.NET MVC 5 application and I have some issues with routing. We are using the attribute Route to map our routes in the web application. I hav

相关标签:
2条回答
  • 2020-12-03 07:07
    //its working with mvc5
    [Route("Projects/{Id}/{Title}")]
    public ActionResult Index(long Id, string Title)
    {
        return view();
    }
    
    0 讨论(0)
  • 2020-12-03 07:23

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

    This is how I did it

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

    And my routing file

    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
    

    or

    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...

    0 讨论(0)
提交回复
热议问题