gpt4 book ai didi

c# - ASP.NET Web Api 路由中断

转载 作者:行者123 更新时间:2023-11-30 20:23:40 27 4
gpt4 key购买 nike

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

这是我的 Controller :

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.

带或不带整数参数。

最佳答案

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

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

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

关于c# - ASP.NET Web Api 路由中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420013/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com