1
votes

Based on documentaion

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

I want every route to start with api. For example i want the route to be http://localhost:40000/api/client/{id}/batch/approve so here is my WebApiConfig class

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Then in controller i have

public class BatchController : ApiController
{
    private readonly MyService _service;
    public BatchController(MyService service)
    {
        _service = service;
    }

    [HttpPost]
    [Route("client/{id}/batch/approve")]
    public async Task<IHttpActionResult> Approve(int id, RequestDTO request)
    {
        return Ok(await _service.Approve(clientID,request).ConfigureAwait(false));
    }

When client invoke this route, it receives 404 Not Found response. However if i prefix api in Route attribute like below then it worked

    [Route("api/client/{id}/batch/approve")]

Why convention based routing not prefixing api to route, why i also need to explicitly add api prefix to Route attribute

1
Because they are completely separate routes in the route table. You can add a route prefix to the controller to avoid having to repeat it on the action sNkosi

1 Answers

0
votes

You must set RoutePrefixAttribute for the controller:

[RoutePrefix("api")] public class BatchController : ApiController { [HttpPost] [Route("client/{id}/batch/approve")] public async Task<IHttpActionResult> Approve(int id, RequestDTO request) { ... } }

https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2