How to do it...

  1. Here is the first way, inserting a constraint when creating a route conventionally:
app.UseMvc(routes => 
            { 
                routes.MapRoute( 
                    name: "default", 
                    template: "{controller=Home}/{action=Index}/{id?}" 
                ); 
 
                routes.MapRoute( 
                    name: "products", 
                    template: "Products/{id=1}", 
                    defaults: new { controller = "Product", action = "Details" } 
                ); 
            }); 
  1. This is the second way, inserting a constraint by attribute routing:
// for an api controller [Route("api/[controller]")] public class ProductValuesController : Controller { // GET api/productvalues/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // PUT api/productvalues/laptop [HttpPut("{name:alpha:length(3)}")] public void UpdateProductName(string name) { } } // for a MVC controller ...

Get ASP.NET Core MVC 2.0 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.