C#中的Web API路由

3
我正在尝试构建一个Web API,该API将接受两个参数。然而,在调用API时,它总是没有任何参数就命中了该方法。 我按照这里的说明进行操作,但无法弄清楚为什么它不起作用。
我使用'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 没有太多更改,除了它现在接受两个参数:
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."}

2
@kodi,你的路由与请求不匹配。如果你将参数重命名为方法id1和id2,会发生什么? - George Stocker
@GeorgeStocker 我不知道参数名称必须匹配。非常感谢你,问题解决了。 - idok
@GeorgeStocker:有没有一种方式可以使webApiConfig中的参数名称更加灵活,以便id1、id2自动映射到方法参数? - idok
@GeorgeStocker,您能将此发布为答案,以便我接受吗? - idok
@kodi 当然,我还添加了一些更多的信息。 - George Stocker
2个回答

3

为了使路由引擎将请求路由到正确的动作,首先它会查找其参数与路由名称匹配的方法。

换句话说:

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

匹配:

public void Get(string id1, string id2) {}

但不包括:

public void Get(string type, string slug) {}

如果你愿意,这种方法也可以起作用:
http://localhost?type=weeeee&slug=herp-derp

这将与之匹配

public void Get(string type, string slug)

0

在你的路由配置中,必须使用名为id1和id2的参数名。 就像这样:

// Get : api/test/type/slug
public void Get(string id1,string id2){
    //Doesn't reach here
}

明白了,谢谢。有没有一种方法可以配置webApiConfig,使我可以在那里拥有一个通用路径,这样我就不必在方法中使用id、id2了? - idok
将当前行中的变量名称从“routeTemplate:“api/{controller}/{id1}/{id2}”更改为“routeTemplate:“api/{controller}/{type}/{slug}”。 - Paul Carroll
感谢@PaulCarroll:我之所以要求通用路径,是因为我在另一个控制器中有另一种方法,该方法接受2个不同的参数。比如说:public void method2(string blah1,string blah2)。我想知道是否有一种解决方案,可以在WebApiConfig中使用通用内容,这样每次添加方法时就不必更改它了。 - idok
你可以使用复杂对象作为参数,并设置路由配置。 像这样: routeTemplate: "api/{controller}/{action}", - Jay Hu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接