我的控制器中有两个动作方法。
[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);
}
}
以下是我的路线配置文件
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) }
);
我打电话给以下
localhost/User - - Working
localhost/User/Jane -- Not working throwing error.
我不确定API有什么问题。
答案 0 :(得分:3)
您需要在基于约定的路由
之前启用属性路由config.MapHttpAttributeRoutes()
并且还更新控制器。尽量不要在同一个控制器中混合使用基于约定的路径和属性路径
[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) { ... }
}