如果 URL 中未提供任何操作,Web API 似乎有一个内置的默认逻辑使用 HTTP 动词作为操作名称。例如,我有这条路线:
config.Routes.MapHttpRoute(
name: "DefaultApiController",
routeTemplate: "api/{controller}"
);
这是我的行动:
public IEnumerable<Conference> Get()
{
...
}
[ActionName("current")]
public IEnumerable<Conference> GetCurrent()
{
...
}
当我使用 GET 动词转到~/Conferences时,它会将您带到“Get()”操作。如果使用 POST 动词,它会将您带到“Post([FromBody]Conference value)”动作......等等。但是,当您尝试转到 ~/Conferences/GetCurrent 时会发生冲突(即使我在顶部有 [ActionName("current")]):
找到与请求匹配的多个操作: System.Collections.Generic.IEnumerable
1[MyApp.Models.Conference] Get() on type MyApp.Api.ConferencesController System.Collections.Generic.IEnumerable
1[MyApp.Models.Conference] GetCurrent() on type MyApp.Api.ConferencesController
这意味着框架使用 StartsWith 而不是 Equal 来确定默认操作。在将动词与动作匹配时,它也会忽略 ActionName 属性。
我的问题是如何使框架的默认操作与动词完全匹配,而不是使用 StartsWith 逻辑?GET 动词应该只匹配 Get() 动作,而不是 Get()、GetCurrent() GetPast() 等(尤其是当它忽略 ActionName 属性时)。
编辑 为简单起见,我只在上面展示了我的一条路线。我认为如果我显示所有仍在草稿中的路线可能会有所帮助。我正在尝试获得一个完全正常工作的 REST API,同时仍然为添加我自己的自定义操作留出空间:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApiControllerActionId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: null,
constraints: new { action = @"^[a-zA-Z]+$", id = @"^\d+$" } // action must start with character
);
config.Routes.MapHttpRoute(
name: "DefaultApiControllerActionName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { action = @"^[a-zA-Z]+$", name = @"^[a-zA-Z]+$" } // action and name must start with character
);
config.Routes.MapHttpRoute(
name: "DefaultApiControllerId",
routeTemplate: "api/{controller}/{id}",
defaults: null,
constraints: new { id = @"^\d+$" } // id must be all digits
);
config.Routes.MapHttpRoute(
name: "DefaultApiControllerAction",
routeTemplate: "api/{controller}/{action}",
defaults: null,
constraints: new { action = @"^[a-zA-Z]+$" } // action must start with character
);
config.Routes.MapHttpRoute(
name: "DefaultApiController",
routeTemplate: "api/{controller}"
);
更新 似乎添加 HTTP 动词约束有助于:
config.Routes.MapHttpRoute(
name: "DefaultApiControllerGet",
routeTemplate: "api/{controller}",
defaults: new { action = "Get" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
config.Routes.MapHttpRoute(
name: "DefaultApiControllerPost",
routeTemplate: "api/{controller}",
defaults: new { action = "Post" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }
);
config.Routes.MapHttpRoute(
name: "DefaultApiControllerPut",
routeTemplate: "api/{controller}",
defaults: new { action = "Put" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) }
);
config.Routes.MapHttpRoute(
name: "DefaultApiControllerDelete",
routeTemplate: "api/{controller}",
defaults: new { action = "Delete" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Delete) }
);