9

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 } ); } } 

2 Answers 2

10

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" }; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

I want to define the versioning at the controller level rather than every action. I mean the prefix "v1" or "v2" when we upgrade the API
Please avoid to add verbs in resources. The 'get' word should never appear in a restful URL. Even though it is just a dummy example, dummy 'bad practices' tent to find their way in production environments.
5

You are mixing up how attribute routing and convention-based routing work.

This is full attribute routing.

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

If you want to do the same thing via convention-based routing

public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DummyApi", routeTemplate: "api/v2/dummy/{action}", defaults: new { controller = "Dummy" } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.