Welcome to our comprehensive guide on ASP .NET Routing! In this tutorial, we'll delve into the world of URL routing, a powerful feature of ASP .NET that allows you to create clean, user-friendly URLs for your web applications. Let's get started!
Routing in ASP .NET is all about mapping URLs to the correct controller actions. It helps in creating URLs that are easy to understand and remember, making your application more user-friendly.
To create a route, we use the RouteTable.Routes.Add method in the Application_Start event of the global application class. Let's create a simple route.
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(
new Route("about/{name}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary { { "controller", "Home" }, { "action", "About" } }
}
);
}
}In the above example, we've created a route for the URL /about/{name}. The {name} is a placeholder that will be replaced with the actual value.
Let's create a simple example.
We'll create a simple controller and action that displays a message.
public class HomeController : Controller
{
public ActionResult About()
{
return View();
}
public ActionResult DisplayMessage(string message)
{
ViewData["Message"] = message;
return View();
}
}Now, let's route these actions.
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(
new Route("", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary { { "controller", "Home" }, { "action", "About" } }
}
);
RouteTable.Routes.Add(
new Route("about", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary { { "controller", "Home" }, { "action", "DisplayMessage" } }
}
);
RouteTable.Routes.Add(
new Route("about/{message}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary { { "controller", "Home" }, { "action", "DisplayMessage" } }
}
);
}
}Now, if you navigate to /about, it will show the About page. If you navigate to /about/Hello World, it will display the message "Hello World".
Nested routes help in creating more complex routes. Let's create a nested route for a blog.
public class BlogController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Post(int id)
{
return View();
}
}public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(
new Route("blog/{year}/{month}/{day}/{title}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary { { "controller", "Blog" }, { "action", "Post" } }
}
);
}
}Now, if you navigate to /blog/2022/12/31/My-First-Post, it will display the post with the specified date and title.
What does routing do in ASP .NET?
That's it for our Routing Introduction tutorial! In the next lesson, we'll dive deeper into routing and learn how to create custom routes and handle route constraints. Stay tuned! 🚀