I have two action method in my controller.
[RoutePrefix("user")]
public class UserController: ApiController
{
[HttpGet]
public IEnumerable<User> Get()
{
return new User.GetUsers();
}
[Route("{name}")]
[HttpGet]
public IEnumerable<User> GetByName(string name)
{
return new User.GetUsers(name);
}
}
Below is my route config file
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { controller = "user", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApiGet",
routeTemplate: "{controller}/{id}",
defaults: new { action = "Get", id= RouteParameter.Optional },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
I am calling the following
localhost/User - - Working
localhost/User/Jane -- Not working throwing error.
I am not sure what is wrong with the API.
you need to enable attribute routing config.MapHttpAttributeRoutes()
before convention-based routes
And also update controller. Try not to mix convention-based and attribute routes in the same controller
[RoutePrefix("user")]
public class UserController: ApiController
{
//GET user
[Route("")]
[HttpGet]
public IEnumerable<User> Get() { ... }
//GET user/Jane
[Route("{name}")]
[HttpGet]
public IEnumerable<User> GetByName(string name) { ... }
}