How to make url definitions from Controller Actions in .NET MVC?
Posted On : Aug 20, 2020This can be done at two steps; first, call the MapMvcAttributeRoutes function of "routes" variable derived from RouteCollection under the default function RegisterRoutes in the RouteConfig.cs to enable url routing via Actions, then configure the urls as you want in the Controllers like below.
Sample RouteConfig.cs file;
using System.Web.Mvc; using System.Web.Routing; namespace KaanCamur { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // We just call the MapMvcAttributeRoutes() function of "routes" variable derived from RouteCollection here, that's all. Other codes you see here are created by system as default. routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Eng", action = "Index", id = UrlParameter.Optional } ); } } }
Sample Controller.cs file;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
namespace KaanCamur.Controllers
{
public class EngController : Controller
{
// The "Index" Action will be triggered when requested "Eng/Home" url in address bar.
[Route("Eng/Home")]
public ActionResult Index()
{
return View()
}
// The "Contact" Action will be triggered when requested "Eng/Contact" url in address bar.
[Route("Eng/Contact")]
public ActionResult Contact()
{
return View()
}
// The "Products" Action will be triggered when requested "Eng/Products" url in address bar.
[Route("Eng/Products")]
public ActionResult Products()
{
return View()
}
// The "MyNotes" Action will be triggered when requested "Eng/Blog" url in address bar.
[Route("Eng/Blog")]
public ActionResult MyNotes()
{
return View()
}
}
}