Google News
logo
ASP.NET - Interview Questions
Explain how attribute-based routing works?
Attribute routing is an alternative routing strategy for conventional routing. It is often used to create REST API endpoints for web services. It uses a set of attributes to map action methods directly to route templates.
 
Attribute routing directly defines the routes on action methods. We can also use these attributes on the controllers. It enables us to get fine-grained control over what routes map to which actions. With attribute routing, the controller and action names play no part in determining the action method.
 
For example, we use attributes Blog and Home to map an incoming URL such as myapp.com/blog/post/3 to the Show method on the PostsController.
[Route("blog")]
public class PostsController : Controller
{
  [HttpGet("post/{id:int}")]
  public IActionResult Show(int id = 0)
  {
      Post post = new Post()
      {
          ID = id
      };

      return View("Show", post);
  }

  [HttpGet("edit/{id:int}")]
  public IActionResult Edit(int id)
  {
      Post postToEdit = _service.Get(id);

      return View("Edit", postToEdit);
  }
}
In the above example, the attribute [Route(“blog”)] is placed on the controller, whereas the route [HttpGet(“post/{id:int}”)] is placed on the action method. A controller route applies to all actions in that controller. For example, the second [“edit/{id:int}”] route matches the url myapp.com/blog/edit/3.
 
In addition to the above route templates, ASP.NET Core provides the following HTTP verb templates.
 
* [HttpGet]
* [HttpPost]
* [HttpPut]
* [HttpDelete]
* [HttpHead]
* [HttpPatch]
Advertisement