WebAPI2 and MVC5 route config

2019-09-01 18:39发布

问题:

I have coded a C# ASP.net MVC5 internet application that works well and I can do CRUD operations using a Person model.

I have added a WebAPI2 controller that uses the entity framework but am getting errors when trying to browse to any of the WebAPI controller methods.

The WebAPI2 controller is called PersonAPIController. The Getpeople method has the // GET api/PersonAPI comment above the method, yet when browsing to this method, I am getting this error:

The resource cannot be found.

Is this a routing issue?

I have a RouteConfig and a WebApiConfig. Do these two configs need to be combined?

Here is the contents of RouteConfig:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Here is the contents of WebApiConfig:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Currently, this is my Application_Start method:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Does the WebApiConfig.Register() line of code need to be added before the RouteConfig.RegisterRoutes(RouteTable.Routes)?

If so, what is the parameter that need to be added to the WebApiConfig.Register() method?

Thanks in advance

EDIT

Here is the exact code to use:

GlobalConfiguration.Configure(WebApiConfig.Register);

回答1:

Make sure that to call Register(HttpConfiguration config) before RegisterRoutes(RouteCollection routes). The sequence matters.



回答2:

Call /api/personapi rather than /api/personapi/getpeople