2017-07-04 171 views
2

我知道已经存在这样的问题,但是由于旧的.NET MVC版本,上下文可能会有很大差异。找不到与名为'something'的控制器匹配的类型MVC 5.2

在本地主机上点击路由"/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”的主线按预期工作。

我在我的控制器中配置了路由。

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

有谁知道那是什么问题?

回答

1

你在混合框架。决定你想要哪一个。 MVC或Web API。

归属路由因为映射到默认MVC路由而起作用。

从控制器的名称和配置的路由,这里的假设是您要使用Web API。

您已经配置了Web API,所以现在只需修复API控制器以从适当的类型派生。

[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); 
    }  
} 
相关问题