Web API 2 Routing - Route Attribute

The question is about defining custom routes using the Route attribute.

I know that in the WebApiConfig class you always define the default route,

 configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); 

I cannot work when I want to pass another parameter. I know I can do this (the code below is defined below the default route specified above):

  //configuration.Routes.MapHttpRoute( // name: "GetBrandImagePaths", // routeTemplate: "api/{controller}/{id}/{type}"); 

But I would rather use custom routing instead of defining all of these routes in the WebApiConfig file. However, if I don't have the code with comments above in the file, I get 404 .. There I believe that custom Route is not even considered.

 public class HelperApiController : ApiController { [HttpGet] [Route("api/helperapi/{id}/{type}")] public string GetBrandImages(int id, string type) { ..... } } 

How to do this so that I can use the routes defined in the WebApiConfig file and define custom routes inside individual API controllers.

Please note that this project is also an MVC project (not just WebApi). Is there something that I don't see is wrong, etc.? I know that there are numerous messages that determine how to pass several parameters, but I think my question is a little more specific as to why it works, and not another.

+6
source share
2 answers

You need to call config.MapHttpAttributeRoutes() .

This will parse all Controller classes and derive routes from the attributes.

I would not mix this with standard routing.

+13
source

Attribute Routing in ASP.NET Web API 2

Enabling Attribute Routing

To enable attribute routing, call MapHttpAttributeRoutes during configuration. This extension method is defined in the System.Web.Http.HttpConfigurationExtensions Class .

 using System.Web.Http; namespace WebApplication { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); // Other Web API configuration not shown. } } } 

Attribute routing can be combined with legend-based routing. To define convention-based routes, call the MapHttpRoute method.

 public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Attribute routing. config.MapHttpAttributeRoutes(); // Convention-based routing. config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } 
+5
source

Source: https://habr.com/ru/post/1012229/


All Articles