Part - 4 : ASP.NET MVC Interview Question's Answer


16. How to define a route in ASP.NET MVC?

You can define a route in ASP.NET MVC as given below:
public static void RegisterRoutes(RouteCollection routes)
 {
   routes.MapRoute(
   "Default", // Route name
   "{controller}/{action}/{id}", // Route Pattern
   new
    {
      controller = "Home",
      action = "Index",
      id = UrlParameter.Optional
    }  // Default values for above defined parameters );
 }

 protected void Application_Start()
  {
    RegisterRoutes(RouteTable.Routes);
    //TODO:
  }
Always remember route name should be unique across the entire application. Route name can’t be duplicate. In above example we have defined the Route Pattern {controller}/{action}/{id} and also provide the default values for controller, action and id parameters. Default values means if you will not provide the values for controller or action or id defined in the pattern then these values will be serve by the routing system. Suppose your webapplication is running on www.example.com then the url pattren for you application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system. Here is a list of URLs that match and don't match this route pattern.

Request URL

Parameters

http://example.com/ controller=Home, action=Index, id=none, Since default value of controller and action are Home and Index respectively
http://example.com/Admin controller=Admin, action=Index, id=none, Since default value of action is Inde
http://example.com/Admin/Product controller=Admin, action=Product, id=none
http://example.com/Admin/Product/1 controller=Admin, action=Product, id=1
http://example.com/Admin/Product/SubAdmin/1 No Match Found
http://example.com/Admin/Product/SubAdmin/Add/1 No Match Found
Note : Always put more specific route on the top order while defining the routes, since routing system check the incoming URL pattern form the top and as it get the matched route it will consider that. It will not checked further routes after matching pattern.

17. What is Attribute Routing and how to define it?

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. Controller level routing – You can define routes at controller level which apply to all actions within the controller unless a specific route is added to an action.
[RoutePrefix("MyHome")]
[Route("{action=index}")] //default action
public class HomeController : Controller
 {
   //new route: /MyHome/Index
   public ActionResult Index()
    {
      return View();
    }

  //new route: /MyHome/About
  public ActionResult About()
   {
     ViewBag.Message = "Your application description page.";
     return View();
   }

  //new route: /MyHome/Contact
  public ActionResult Contact()
   {
     ViewBag.Message = "Your contact page.";
     return View();
   }
 }
2. Action level routing – You can define routes at action level which apply to a specific action with in the controller.
public class HomeController : Controller
 {
   [Route("users/{id:int:min(100)}")] //route: /users/100
   public ActionResult Index(int id)
    {
      //TO DO:
      return View();
    }

  [Route("users/about")] //route" /users/about
  public ActionResult About()
   {
     ViewBag.Message = "Your application description page.";
     return View();
   }

  //route: /Home/Contact
  public ActionResult Contact()
   {
     ViewBag.Message = "Your contact page.";
     return View();
   }
 }
Note :
  • Attribute routing should configure before the convention-based routing.
  • When you combine attribute routing with convention-based routing, actions which do not have Route attribute for defining attribute-based routing will work according to convention-based routing. In above example Contact action will work according to convention-based routing.
  • When you have only attribute routing, actions which do not have Route attribute for defining attribute-based routing will not be the part of attribute routing. In this way they can’t be access from outside as a URI.

18. When to use Attribute Routing?

The convention-based routing is complex to support certain URI patterns that are common in RESTful APIs. But by using attribute routing you can define these URI patterns very easily. For example, resources often contain child resources like Clients have orders, movies have actors, books have authors and so on. It’s natural to create URIs that reflects these relations like as: /clients/1/orders. This type of URI is difficult to create using convention-based routing. Although it can be done, the results don’t scale well if you have many controllers or resource types. With attribute routing, it’s pretty much easy to define a route for this URI. You simply add an attribute to the controller action as:
[Route("clients/{clientId}/orders")]
public IEnumerable GetOrdersByClient(int clientId)
 {
   //TO DO
 }

19. How to enable Attribute Routing in ASP.NET MVC?

Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to routes.MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig.cs file
public class RouteConfig
 {
  public static void RegisterRoutes(RouteCollection routes)
   {
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     //enabling attribute routing
     routes.MapMvcAttributeRoutes();
   }
 }
You can also combine attribute routing with convention-based routing.
public class RouteConfig
 {
  public static void RegisterRoutes(RouteCollection routes)
   {
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     //enabling attribute routing
     routes.MapMvcAttributeRoutes();
     //convention-based routing
     routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "Home", action = "Index", id = 
     UrlParameter.Optional });
   }
 }

20. How to define Attribute Routing for Area in ASP.NET MVC?

You can also define attribute routing for a controller that belongs to an area by using the RouteArea attribute. When you define attribute routing for all controllers with in an area, you can safely remove the AreaRegistration class for that area.
[RouteArea("Admin")]
[RoutePrefix("menu")]
[Route("{action}")]
public class MenuController : Controller
 {
   // route: /admin/menu/login
   public ActionResult Login()
    {
      return View();
    }

   // route: /admin/menu/products
  [Route("products")]
  public ActionResult GetProducts()
   {
     return View();
    }

  // route: /categories
  [Route("~/categories")]
  public ActionResult Categories()
   {
     return View();
   }
 }
0 Komentar untuk "Part - 4 : ASP.NET MVC Interview Question's Answer"

Back To Top