【发布时间】:2015-03-20 16:07:35
【问题描述】:
我正在尝试构建一个可以接受 2 个参数的 Web API。但是,在调用 API 时,它总是会在没有任何参数的情况下命中该方法。 我按照here 中的说明进行操作,但不知道为什么它不起作用。
我使用“PostMaster”Chrome 扩展程序发送的请求:http://localhost:51403/api/test/title/bf
对于上述请求,我希望第一种方法会被命中,但第二种方法正在达到。
控制器内的方法是:
// Get : api/test/type/slug
public void Get(string type,string slug){
//Doesn't reach here
}
// Get : api/test
public void Get() {
// Reaches here even when the api called is GET api/test/type/slug
}
webApiConfig 没有太大变化,除了它接受 2 个参数:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id1}/{id2}",
defaults: new { id1 = RouteParameter.Optional, id2 = RouteParameter.Optional }
);
}
我从文档中的理解是 webapiconfig 不必更改。 这是我得到的错误
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:51403/api/test/title/bf'.",
"MessageDetail":"No action was found on the controller 'test' that matches the request."}
【问题讨论】:
-
@kodi 您的路线与您的要求不符。如果将参数重命名为该方法 id1 和 id2,会发生什么?
-
@GeorgeStocker 我不知道参数名称必须匹配。太感谢了。做到了。
-
@GeorgeStocker : 有没有办法让 webApiConfig 中的参数名称更灵活,这样 id1,id2 会自动映射到方法参数?
-
@GeorgeStocker 您能否将其发布为答案以便我接受?
-
@kodi 当然,我还添加了更多信息。
标签: c# asp.net api routes asp.net-web-api-routing