Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Routing Attribute

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 or
localhost:11045/Home/Index/?id=98.

How to handle this using routing attribute.

My Action in Controller look like below.

public ActionResult Index() 
{
  return View(); 
}
like image 670
user1389320 Avatar asked Jun 29 '16 14:06

user1389320


People also ask

Can you enable attribute routing in MVC 5?

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.

What is routing in MVC 5 with example?

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.

What is the use of route attribute in MVC?

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.


1 Answers

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 = "" }
        );
    }
}
like image 120
Nkosi Avatar answered Sep 28 '22 11:09

Nkosi