wesleyy
wesleyy

Reputation: 2735

No type was found that matches the controller named 'something' MVC 5.2

I know there are already such questions, but the context there is very different probably because of the older .NET MVC versions.

I am getting the error No type was found that matches the controller named 'employee' when hitting the route "/api/employee/5" on the localhost. The entire route is like "127.0.0.1:8080/api/employee/5". The home route at "127.0.0.1:8080" works as expected.

I have configured the route in my 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");
    }

}

I made no changes to the WebApiConfig.cs and it looks like follows.

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

Does anyone know what is the issue with that?

Upvotes: 3

Views: 877

Answers (1)

Nkosi
Nkosi

Reputation: 246998

You are mixing frameworks. Decide which one you want. MVC or Web API.

The home route works because it is mapping to the default MVC route.

From the name of the controller and the configured routes the assumption here is that you want to use Web API.

You already have the Web API configured so now it is just to fix the API controller to derive from the appropriate type.

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

Upvotes: 3

Related Questions