简体   繁体   中英

ASP.NET MVC - About Constraints in Routes

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)

路线

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.

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*" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM