ASP.NET Web Api 路由损坏

ASP.NET Web Api Routing Broken

我无法在我的 asp.net 网络 api 项目中使用基本路由。我遵循了 asp.net (http://www.asp.net/web-api/overview/web-api-routing-and-actions) 上的示例,并且在整个 Whosebug 中进行了搜索,试图找到解决方案。无论我尝试过什么示例,我都无法使属性路由起作用。

这是我的控制器:

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 结束,或者在上面的代码中,我收到消息

No HTTP resource was found that matches the request URI 'http://localhost:2442/api/employee/1'.

No action was found on the controller 'Employee' that matches the request.

带或不带整数参数。

您是否试过像这样将 RoutePrefix 属性放在 class 上:

[RoutePrefix("api/employee")]
public class EmployeeController : ApiController

要么为您的控制器使用属性路由,要么不要全部使用它。这意味着你需要用 RoutePrefix 装饰你的控制器,而不是依赖于配置的路由。

[RoutePrefix("api/employee")
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}")]
    public Employee GetEmployee(int id)
    {
        return _employees.Queryable().FirstOrDefault();
    }
}

或者在下面的例子中,我们依赖定义的路由,而不是使用属性路由。

public class EmployeeController : ApiController
{
    private readonly IRepository<Employee> _employees; 
    public EmployeeController(IRepository<Employee> repo)
    {
        _employees = repo;
    }
    public IEnumerable<Employee> GetEmployees()
    {
        return _employees.Queryable();
    }
    public Employee GetEmployee(int id)
    {
        return _employees.Queryable().FirstOrDefault();
    }
}

如果你混合搭配,它会混淆事情。