Search code examples
c#asp.net-web-api2asp.net-web-api-routing

Web API 2 RoutePrefix does not working


When defining a RoutePrefix at controller level, when I try to access the API class using the URL with prefix http://localhost:55020/api/v2/dummy/get it throws 404. This http://localhost:55020/api/dummy/get works absolutely fine though.

Here is controller class which has a RoutePrefix defined

    [RoutePrefix("v2/dummy")]
    public class DummyController : ApiController
    {
        // GET api/values
        [SwaggerOperation("Get")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2", "value3" };
        }
    }

Here is WebApiConfig

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

Solution

  • Use attribute routing instead

    public class DummyController : ApiController
    {
        // GET api/values
        [HttpGet]
        [Route("api/v2/dummy/get")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2", "value3" };
        }
    }
    

    and if you want route prefix then

    [RoutePrefix("api/v2/dummy")]
    public class DummyController : ApiController
    {
        // GET api/v2/dummy
        [HttpGet]
        [Route("get")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2", "value3" };
        }
    }