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 have the following action:
[Route("{type}/{library}/{version}/{file?}/{renew?}")] public ActionResult Index(EFileType type, string library, string version, string file = null, ECacheType renew = ECacheType.cache) { // code... }
We only can access this URL if we pass the slash char /
in the end of url
, like this:
type/lib/version/file/cache/
It works fine but does not work without /
, I get a 404
not found error, like this
type/lib/version/file/cache
or this (without optional parameters):
type/lib/version
I would like to access with or without /
char at the end of url
. My two last parameters are optional.
My RouteConfig.cs
is like this:
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } }
How can I solve it? Make the slash /
be optional too?
You need to provide at least two parameters in MapRoute, route name, and URL pattern.
Routing is a pattern matching system. Routing maps an incoming request (from the browser) to particular resources (controller & action method). This means routing provides the functionality to define a URL pattern that will handle the request. That is how the application matches a URI to an action.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With