I'm trying to use attribute routing in my application. I provided the route attributes to all action methods and also provided the HTTP verbs to the action methods. But I am not able to set the default routing. If I manually provided the route in the URL, it's working but not able to see by default on application running. I used the empty [route("")]
attribute for default.
Controller code :
namespace WebApplication2.Controllers
{
[RoutePrefix("myproject")]
public class AttributerouteController : Controller
{
// GET: Attributeroute
[HttpGet]
[Route("")]
public ActionResult Employees()
{
return View();
}
[HttpGet]
[Route("Employees/{id}")]
public ActionResult Employeebyid(int id)
{
return View();
}
[HttpGet]
[Route("Employees/{id}/department")]
public ActionResult Empdepartment(int id)
{
return View();
}
}
}
My routeconfig.cs
code :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.RouteExistingFiles = true;
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Attributeroute", action = "Employees", id = UrlParameter.Optional }
);
}
Use a tilde ~
on the method attribute to override the route prefix if needed:
[RoutePrefix("myproject")]
public class AttributerouteController : Controller
{
[Route("~/")]
public ActionResult Employees()
{
return View();
}
[Route("Employees/{id}")] //http://localhost:12345/myproject/Employees/66
public ActionResult Employeebyid(int id)
{
//return View(nameof(Employees));
}
[Route("Employees/{id}/department")] // http://localhost:12345/myproject/Employees/66777/department
public ActionResult Empdepartment(int id)
{
//return View(nameof(Employees));
}
}
By the way, you can omit the HttpGet attribute on the action methods. It is the default HTTP verb.
An additional useful information you can find on the Microsoft blog, here: Attribute Routing in ASP.NET MVC 5