简体   繁体   English

ASP.NET MVC-关于路由约束

[英]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 以下是我的类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' 以下是我的控制器“ 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? 我想限制用户输入另一个数字,但是当我施加约束[constraints: new {id = @"\\d+"}]我的URL最终采用了“默认”路由,为什么会这样? (I'm new to MVC, I do not understand much about routes). (我是MVC的新手,我对路由了解不多)。

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. 对于这样的简单方案,可以使用这种Regex模式。 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 但是,要获得适当的约束(尤其是在使用自定义约束时),应通过继承IRouteConstraint接口来创建自己的约束

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, 然后在RouteConfig中注册它,如下所示:

 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+ ASP.NET MVC中也讨论了此问题:带有可选参数的路由,但如果提供,则必须与\\ d +匹配

The short answer is: use this constraint pattern: id = @"\\d*" . 简短的答案是:使用此约束模式: id = @"\\d*"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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