I have the Home Controller and my Action name is Index. In My route config the routes like below.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Now I call my page like http://localhost:11045/Home/Index
is correct.
If I call my page like following it should redirect to error page.localhost:11045/Home/Index/98
orlocalhost:11045/Home/Index/?id=98
.
How to handle this using routing attribute.
My Action in Controller look like below.
public ActionResult Index()
{
return View();
}
Enabling Attribute RoutingTo enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration. We can also add a customized route within the same method. In this way we can combine Attribute Routing and convention-based routing.
Routing is a pattern matching system. Routing maps an incoming request (from the browser) to particular resources (controller & action method). This means routing provides the functionality to define a URL pattern that will handle the request. That is how the application matches a URI to an action.
ASP.NET MVC5 and WEB API 2 supports a new type of routing, called attribute routing. In this routing, attributes are used to define routes. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.
For Attribute Routing in ASP.NET MVC 5
decorate your controller like this
[RoutePrefix("Home")]
public HomeController : Controller {
//GET Home/Index
[HttpGet]
[Route("Index")]
public ActionResult Index() {
return View();
}
}
And enable it in route table like this
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//enable attribute routing
routes.MapMvcAttributeRoutes();
//convention-based routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = "" }
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With