ASP.NET MVC - About Constraints in Routes

3.1k views Asked by At

I'm having difficulty using a constraint on a custom route. The following is my class RouteConfig.cs

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "produtos",
                url: "produtos/{action}/{id}",
                defaults: new { controller = "Produto", action = "Listar", id = UrlParameter.Optional },
                constraints: new { id = @"\d+" }
            );

            routes.MapRoute(
                name: "Default",
                url: "{action}/{controller}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

and the following is my Controller 'Produto'

public class ProdutoController : Controller
    {

        MozitMVCContext _context = new MozitMVCContext();

        [HttpGet]
        public ActionResult Cadastrar()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Cadastrar(Produto produto)
        {
            if (ModelState.IsValid)
            {
                _context.Produtos.Add(produto);
                _context.SaveChanges();

                return RedirectToAction("Cadastrar");
            }

            return View(produto);
        }

        [HttpGet]
        public ActionResult Alterar(int id)
        {
            var produto = _context.Produtos.Find(id);
            return View(produto);
        }

        [HttpPost]
        public ActionResult Alterar(Produto produto)
        {
            if (ModelState.IsValid)
            {
                _context.Produtos.Attach(produto);
                _context.Entry(produto).State = EntityState.Modified;
                _context.SaveChanges();
                return RedirectToAction("Listar");
            }

            return View(produto);
        }

        public ActionResult Listar()
        {
            var produto = _context.Produtos.ToList();

            return View(produto);
        }

        public ActionResult Detalhes(int id)
        {
            var produto = _context.Produtos.Find(id);
            return View(produto);
        }

        public ActionResult Excluir(int id)
        {
            _context.Produtos.Remove(_context.Produtos.Find(id));
            _context.SaveChanges();
            return RedirectToAction("Listar");
        }

    }

I want to restrict the user to enter a different one number digit, however when I put the constraint [constraints: new {id = @"\d+"}] my URL ends up taking the 'Default' route, why does this happen? (I'm new to MVC, I do not understand much about routes).

I'm trying to follow a video course and make my code work, I include an Image: (sorry for quality of image, print of video)

Routes

2

There are 2 answers

0
Dipal Mehta On

For a simpler scenario like this, you can use such Regex pattern. It will work.

But, to get proper hold on constrain especially when using custom constraints, you should create your own Constraint by inheriting IRouteConstraint inteface

public class MyRouteConstratint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            //Logic goes here
            return true;
        }
    }

And in RouteConfig register it like following,

 routes.MapRoute(
                name: "produtos",
                url: "produtos/{action}/{id}",
                defaults: new { controller = "Produto", action = "Listar", id = UrlParameter.Optional },
                constraints: new MyRouteConstratint()
            );

Hope helps.

0
R. Schreurs On

This issue is also discussed in ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+

The short answer is: use this constraint pattern: id = @"\d*".