What is Attribute Routing in ASP.NET Core?
Attribute routing is introduced in ASP.NET MVC 5 and is also available in ASP.NET Core. In Attribute routing we define url pattern directly on Action using a built in attribute [Route]. [Route] is built in attribute which help you to define url pattern for action .To use the attribute routing at first temp you need to enable the attribute routing using endpoint routing as follows –
app.UseEndpoints(endpoints =>{
endpoints.MapControllers();
});
MapControllers() method will activate the attribute routing in asp.net core 3.x application, after activation you can use [Route] Attribute on any controller and action as follows –
[Route("ho/ind")]
public IActionResult Index()
{
return View();
}
So index action can be called using url ho/ind.
You can also define multiple url to one action using attribute routing.
[Route("ho/ind")]
[Route("h/index")]
public IActionResult Index()
{
return View();
}
In this you can call index action using url h/index as well as ho/ind both.
You can also define the parameters in URL
[Route("ho/say/{str}")]
[Route("hom/{str}/say")]
public string SayHello(string str)
{
return "Say Hello Called for :=>" + str;
}
In this str is url parameter and you can pass any value to the str parameter.
You can also define the restriction /constraints to the url parameters as follows
[Route("ho/bye/{n:int:min(10):max(20)}")]
public string SayBye(string n)
{
return " n value is:" + n;
}
here we had added restriction that n is url parameter and it should be integer and the minimum alue for n can be 10 or maximum value for n can be 20.