I am trying to implement alternative routing in an MVC 5 web application.
I have a controller code:
namespace MyMvcProject.Web.Controllers { [RoutePrefix("account")] public class AccountController : Controller { [Route("{param}")] [Authorize] public ActionResult Index(string param = null) { ...
which works great when hitting the URL: http://example.com/account/testparam . However, I would like to have param as an optional parameter.
I tried changing [Route("{param}")] to [Route("{param}*")] , but then the Index() method is never entered. I also tried changing it to [Route("{param:string=Test}")] , but I get a routing error with the term string .
My RoutConfig.cs contains:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{param}", defaults: new { controller = "Home", action = "Index", param = UrlParameter.Optional } ); }
Does anyone know how I can get Index() have an optional parameter using this alternative routing syntax? This is very useful in other parts of my application, so I would like to save the RoutePrefix and Route decorators.
UPDATE
I'm still trying to figure this out, so I changed my route decorator to [Route("{param:int=0}")] and my constructor to public ActionResult Index(int id) , and it works as expected (i.e. http://example.com/account behaves as if http://example.com/account has been entered, which is exactly what I want using only string data types.
When I change the decorator to: [Route("{id:string=\"\"}")] and the constructor to public ActionResult Index(string id) , and I see a runtime error:
The built-in constraint converter like 'DefaultInlineConstraintResolver' could not resolve the following built-in constraint: 'string'.