我知道已经有这样的问题,但可能是因为旧的 .NET MVC 版本,上下文非常不同。
在本地主机上点击路由 "/api/employee/5"
时,我收到错误 No type was found that matches the controller named 'employee'
。整个路由就像“127.0.0.1:8080/api/employee/5”。 “127.0.0.1:8080”处的主路由按预期工作。
我已经在我的 Controller 中配置了路由。
EmployeeController.cs
[Route("api/employee")]
public class EmployeeApiController : Controller
{
[HttpGet, Route("api/employee/{id}")]
public ActionResult GetEmployee(long id)
{
return Content(
new Employee("Bobby", "Smedley",
"London", "Teheran",
EmployeeGender.M,
DepartmentCode.D_2157020,
"12345678901").ToString(),
"application/json");
}
}
我没有对 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 }
);
}
}
有人知道这是什么问题吗?
最佳答案
您正在混合框架。决定你想要哪一个。 MVC 或 Web API。
home 路由有效,因为它映射到默认的 MVC 路由。
根据 Controller 的名称和配置的路由,这里假设您要使用 Web API。
您已经配置了 Web API,所以现在只需修复 API Controller 以从适当的类型派生。
[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController { // <-- Note: API controller
[HttpGet]
[Route("{id:long}")] //Match GET api/employee/5
public IHttpActionResult GetEmployee(long id) { // <-- Note: return type
var model = new Employee("Bobby", "Smedley",
"London", "Teheran",
EmployeeGender.M,
DepartmentCode.D_2157020,
"12345678901");
return Ok(model);
}
}
关于c# - 找不到与名为 'something' MVC 5.2 的 Controller 匹配的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44901575/