Search code examples
c#asp.net-mvcasp.net-mvc-routing

ASP.NET MVC route parameter that may have hyphens


We have a working controller as shown below. The name parameter could be something like "Widget", "A09912", or "W-0-090-B". The routing fails when there is a hyphen in the parameter.

[HttpGet]
[Route( @"Product/{name:alpha}" )]
public ActionResult Index( string name )
{
    IList<Product> list = Repository.GetByName( name );
    return View( list );
}

Is there a way to configure things so that a hyphenated parameter will work?


Solution

  • Yes, there is a way to configure things so that a hyphenated parameter will work.

    Remove the alpha constraint:

    {x:alpha} Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z)

    By including hyphenated parameter it doesn't match the constraint you are currently using.

    Have a look at Route Constraints in Attribute Routing in ASP.NET Web API 2