我已经尝试了所有东西,但看起来我根本就没有得到它。我的WebApiConfig.cs看起来像这样:
config.Routes.MapHttpRoute(
"Default",
"api/{controller}/{id}",
new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(
"AccountVerification",
"api/{controller}/{id}/{action}",
null,
new { controller = "Account" });
我的控制器看起来像这样:
public class AccountController : ApiController {
public HttpResponseMessage GetByKey(Guid accountID) {
...
}
[HttpGet]
[ActionName("Verify")]
public HttpResponseMessage VerifyAccount(Guid accountID) {
...
}
}
这些方法应该会受到以下网址的影响:
GET /api/account - WORKS
GET /api/account/00000000-0000-0000-000000000001 - WORKS
GET /api/account/00000000-0000-0000-000000000001/verify - DOESNT WORK
我尝试了很多东西;我肯定在这里做错了...请帮忙。
答案 0 :(得分:2)
首先,如果你想用假Guid测试,以及有可选的Guid参数,它们必须是Nullable参数(假guid将被反序列化为null):
public class AccountController : ApiController
{
public HttpResponseMessage GetByKey(Guid? accountID)
{
throw new Exception("GetByKey " + (accountID.HasValue ? accountID.ToString() : "NULL"));
}
[System.Web.Http.HttpGet]
[System.Web.Http.ActionName("Verify")]
public HttpResponseMessage VerifyAccount(Guid? accountID)
{
throw new Exception("VerifyAccount "+(accountID.HasValue?accountID.ToString():"NULL"));
}
}
然后,您的映射应该:
使用正确的操作默认值
config.Routes.MapHttpRoute(
"AccountVerification",
"api/{controller}/{accountID}/{action}"
);
config.Routes.MapHttpRoute(
"Default",
"api/{controller}/{accountID}",
defaults: new { Controller="Account", action = "GetByKey", accountID = RouteParameter.Optional }
);
答案 1 :(得分:1)
GET / api / account / 00000000-0000-0000-000000000001 / verify与路由集合中的第一条路由匹配。因此,它从不检查第二条路线是否匹配。将“api / {controller} / {id} / {action}”设置为集合中的第一条路径,它应该可以正常工作。