In this article, we will know how to
We can find the default route template in Startup.cs : Configure
Add the following red codes to support Area routing ruls.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//…Skip
app.UseMvc(routes =>
{
routes.MapRoute(
name:"areaRoute",
template:"{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Now create Areas, for example,
To enable Areas routing, use Area
and Route
attributes like this,
[Area("User")]
[Route("User/[controller]")]
public class AuthController : Controller
{
[Route("[action]")]
public IActionResult Index()
{
ViewBag.Title = "Index";
return View();
}
[Route("[action]")]
public IActionResult Create()
{
ViewBag.Title = "Create";
return View();
}
//[Route("[action]/{page}")] //It's ok to write like this
[Route("[action]/{page:int?}")]
public IActionResult Edit(int? page)
{
ViewBag.Title = "Edit";
ViewBag.Page = page;
return View();
}
[Route("[action]/{data}")]
public IActionResult Edit(String data)
{
ViewBag.Title = "Edit";
ViewBag.Page = data;
return View();
}
}
There is no need to add routing template in WebApi Startup.cs
Just put Route
attribute to assign the routing rules for WebApi’s controllers and actions (Restful methods).
[Route("api/User/[controller]")]
public class AuthController : Controller
{
[HttpGet("GetAll")]
public IEnumerable<string> Get()
{
return new string[] { "auth1", "auth2" };
}
[HttpGet("Get/{id}")]
public string Get(int id)
{
return id.ToString();
}
// POST api/values
[HttpPost]
public void Post(DtoModel model)
{
}
// DELETE api/values/5
[HttpDelete("Delete/{id}")]
public void Delete(int id)
{
}
}
Note that you can add an action name in Http Method attribute like the following to define the action name for the action
[HttpGet("GetAll")]
public IEnumerable<string> Get()
And the HttpGet url will behttp://localhost:14125/api/user/auth/getall
Results in Postman: