Introduction
In ASP.NET Core, Routing is the process of directing an HTTP request to a Controller. Let us understand its working with an example. We have created a Controller (HomeController) in our application which is a C# class that doesn’t need to be derived from a base class, or implement an interface, or to have any special attribute. It is a plain C# class with a name, HomeController, and it contains the Index method which returns a string.
Startup.cs
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- namespace RoutingSample {
- publicclassStartup {
- public Startup(IConfiguration configuration) {
- Configuration = configuration;
- }
- public IConfiguration Configuration {
- get;
- }
-
- publicvoid ConfigureServices(IServiceCollection services) {
- services.AddMvc();
- }
-
- publicvoid Configure(IApplicationBuilder app, IHostingEnvironment env) {
- if (env.IsDevelopment()) {
- app.UseDeveloperExceptionPage();
- }
- app.UseMvc();
- }
- }
- }
HomeController.cs
- using Microsoft.AspNetCore.Mvc;
- namespace RoutingSample.Controllers {
- [Route("[controller]")]
- publicclassHomeController: Controller {
- [HttpGet("Index")]
- publicstring Index() {
- return "Hello, buddy! The message is from Home Controller.!!";
- }
- [HttpGet("State")]
- publicstring State() {
- return "Gujarat";
- }
- [HttpGet("Country")]
- publicstring Country() {
- return "India";
- }
- }
- }
- You can try this as well by changing the URL in the browser. In this example, it is http://localhost:44348/, except that the port might be different.
- If you append /Home or /Home/Index to the URL and press the Enter button, you will see the same result.
Let us run the application in the browser. Once the application is run, you will see the following output.
In this Controller, you can see two action methods − State and Country, which will return just a State and Country name respectively. Let us save this file and specify /Home/State at the end of the root URL.
You can see the State as in the above screenshot. If you specify /Home/Country, you will see the name of the Country too.
Here, the ASP.NET Core MVC goes to the HomeController to specify the route of the method. You can directly access the method through routing.