Web
Analytics
Routing Constraint in Asp.Net MVC | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Before understanding about routing constraints we should have knowledge about routing. Routing is a mechanism by which we can call specific controller and their actions through specified URL.

We can Define Multiple roots into RootConfig.cs file using map route function.

What is Routing Constraint in Asp.Net MVC?

Routing constraint is a mechanism by which we can validate the incoming URL request and response accordingly.

let’s understand by a simple example.

 

  public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
               name: "Default",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, constraints:  new { id = @"\d+" }
           );
            routes.MapRoute(
    "Default2",                                              // Route name
    "{controller}/{action2}/{sid}",                           // URL with parameters
    new { controller = "Home", action = "Index2", sid = "" }  // Parameter defaults
);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NonActionMethod.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index(int id)
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC! Your id is: " + id.ToString();

            return View();
          
        }

        public ActionResult Index2(string sid)
        {
            ViewData["Title"] = "Home Page 2." + sid.ToString();
            ViewData["Message"] = "Welcome to ASP.NET MVC! \"" + sid.ToString() + "\" is an invalid id";

            return View("index");
        }
    }
}
@{
    ViewBag.Title = "Index";
}

<h2> @ViewData["Message"] </h2>