【问题标题】:Web API routing in C#C# 中的 Web API 路由
【发布时间】: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


【解决方案1】:

为了让路由引擎将请求路由到正确的Action,它首先在路由中寻找参数与名称匹配的方法。

换句话说,这个:

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)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 知道了,谢谢。有没有办法配置 webApiConfig,这样我就可以在那里有一个通用路径,所以我不必在方法中有 id,id2?
    • 变量名取自当前读取的行routeTemplate: "api/{controller}/{id1}/{id2}",将其更改为routeTemplate: "api/{controller}/{type}/{slug}"
    • 谢谢@PaulCarroll:我要求一个通用路径,因为我会在不同的控制器中使用另一种方法,它接受 2 个不同的参数。假设:public void method2(string blah1,string blah2)。我想知道是否有一个解决方案可以让我在 WebApiConfig 中拥有一些通用的东西,这样我就不必每次添加方法时都不断更改它。
    • 可以使用复杂对象作为参数,设置路由配置。像这样: routeTemplate: "api/{controller}/{action}",
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多