How do you inherit route prefixes at the controller class level in WebApi?

后端 未结 5 1391
粉色の甜心
粉色の甜心 2021-01-11 10:49

Note, I\'ve read about the new routing features as part of WebApi 2.2 to allow for inheritance of routes. This does not seem to solve my particular issue, however. It seems

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 11:49

    I just ran into this same issue on a .NET Core 3.0 app (seems to be a new feature in MVC 6 so it won't work for MVC 5 and previous versions but may still be helpful for anyone else that stumbles across this problem). I don't have enough rep to make a comment on @EmilioRojo's answer but he is correct. Here is some more information from the Microsoft Docs to help people that come across the same issue.

    Token replacement in route templates ([controller], [action], [area]) For convenience, attribute routes support token replacement by enclosing a token in square-braces ([, ]). The tokens [action], [area], and [controller] are replaced with the values of the action name, area name, and controller name from the action where the route is defined. In the following example, the actions match URL paths as described in the comments:

    [Route("[controller]/[action]")]
    public class ProductsController : Controller
    {
        [HttpGet] // Matches '/Products/List'
        public IActionResult List() {
            // ...
        }
    
        [HttpGet("{id}")] // Matches '/Products/Edit/{id}'
        public IActionResult Edit(int id) {
            // ...
        }
    }
    

    Attribute routes can also be combined with inheritance. This is particularly powerful combined with token replacement.

    [Route("api/[controller]")]
    public abstract class MyBaseController : Controller { ... }
    
    public class ProductsController : MyBaseController
    {
       [HttpGet] // Matches '/api/Products'
       public IActionResult List() { ... }
    
       [HttpPut("{id}")] // Matches '/api/Products/{id}'
       public IActionResult Edit(int id) { ... }
    }
    

提交回复
热议问题