【发布时间】:2015-02-09 21:46:53
【问题描述】:
我无法在我的 asp.net web api 项目中使用基本路由。我遵循了 asp.net (http://www.asp.net/web-api/overview/web-api-routing-and-actions) 上的示例,并在整个 stackoverflow 中进行了搜索,试图找到解决方案。无论我尝试过什么示例,我都无法让属性路由正常工作。
这是我的控制器:
public class EmployeeController : ApiController
{
private readonly IRepository<Employee> _employees;
public EmployeeController(IRepository<Employee> repo)
{
_employees = repo;
}
[Route("")]
public IEnumerable<Employee> GetEmployees()
{
return _employees.Queryable();
}
[Route("{id:int}")]
public Employee GetEmployee(int id)
{
return _employees.Queryable().FirstOrDefault();
}
}
这是我的 Global.asax.cs:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
这是我的 WebApiConfig.cs:
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 }
);
}
}
无论我尝试什么,我都会得到一个 404 或者就像上面的代码一样,我会收到消息
未找到与请求 URI 匹配的 HTTP 资源 'http://localhost:2442/api/employee/1'。
在控制器“员工”上找不到与 请求。
带或不带整数参数。
【问题讨论】: