1

I am trying to set up a WebAPI project using RESTful principles, but I need help with route configuration.

here is the routes that i have declared in the WebAPIConfig.cs

config.Routes.MapHttpRoute(
            name: "API Child Default",
            routeTemplate: "api/v{version}/{controller}/{id}/{child}",
            defaults: new { version = "1", action = "Index", child = RouteParameter.Optional }
        );

config.Routes.MapHttpRoute(
            name: "DefaultApi With Version",
            routeTemplate: "api/v{version}/{controller}/{id}",
            defaults: new { version = "1", action = "Index", id = RouteParameter.Optional }
        );

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

Here is the controller action declaration:

public class EventsController : ApiController
{
    // GET api/v1/Events
    public IEnumerable<string> Get(string version)
    {
        return new string[] { "value1", "value2" };
    }
}  

Here is the request that I came calling that is not finding the controller action: GET /api/v1/Events HTTP/1.1

Can anyone show me why I am getting a not found error when i use the above and how to fix it?

4

1 回答 1

2

问题是您声明的默认操作 ( action = "Index")。如果您删除它,它将正常工作。(因为你没有{action}在你的路由中指定一个参数,它总是会做默认的,即索引,它不存在)。

config.Routes.MapHttpRoute(
            name: "API Child Default",
            routeTemplate: "api/v{version}/{controller}/{id}/{child}",
            defaults: new { version = "1", child = RouteParameter.Optional }
        );

config.Routes.MapHttpRoute(
            name: "DefaultApi With Version",
            routeTemplate: "api/v{version}/{controller}/{id}",
            defaults: new { version = "1", id = RouteParameter.Optional }
        );
于 2013-09-05T02:17:44.027 回答