【问题标题】:Web Api doesn't work when multiple params?多个参数时Web Api不起作用?
【发布时间】:2014-10-04 21:47:52
【问题描述】:

我有两条路线:

 routes.MapRoute(
          name: "Default1",
          url: "{controller}/{action}/{id}/{id2}" 

      );

 routes.MapRoute(
            name: "Default", 
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

我的控制器看起来像:

 public class ProductsController : ApiController
    {
        ...
         public  int GetAll(int id,int id2)
         {
             return 1;
         }

        public Product GetProduct(int id)
        {
          ....
          return item;
        }
     }

当我写信时:http://localhost:9000/api/products/2

它匹配第二条规则并且:

但是当我写http://localhost:9000/api/products/2/3(假设符合第一条规则)时:

问题

我的错误在哪里?

nb:

运行http://localhost:9000/api/products/2?id2=1 确实给出了正确的结果 - 但是,嘿!我专门为这个做了一个路线!

(already read this answer - didn't help much)

【问题讨论】:

    标签: asp.net asp.net-web-api routing


    【解决方案1】:

    我认为您的问题是您在 RouteConfig 而不是 WebApiConfig 中定义了上述路由。 Web Api 路由应该在 WebApiConfig 中定义,如果你看一下你应该会找到默认路由:

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
        );
    }
    

    为了匹配 url:api/products/2/3,您需要在现有默认路由之前向 WebApiConfig 添加新路由:

    config.Routes.MapHttpRoute(
    name: "DefaultApi2",
    routeTemplate: "api/{controller}/{id}/{id2}"
    );
    

    【讨论】:

    • 是的,我读到了你的问题。如果您对我的回答有不清楚的地方,请开始聊天,我很乐意澄清。
    • 天啊。我很抱歉 !对不起 !你是对的 ! (固定)
    【解决方案2】:

    这是您的路线解析方式。

    您需要更改路线的顺序。

    Default放在第一位,Default1放在最后,因为它有更多的目录需要解析。

    【讨论】:

    • 不要忘记为 Default1 路由添加默认参数/属性。这就是您收到错误的原因
    • 这是代码:仍然:错误:public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute... routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Default1", url: "{controller}/{action}/{id}/{id2}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, id2 = UrlParameter.Optional } ); }
    • 在您的路线中将 {controller}/ 更改为 api/,看看会发生什么。
    【解决方案3】:

    您没有在请求中提供操作。因此,要触发您的第一条路线,您需要调用:

    http://localhost:9000/api/products/getall/2/3 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2016-05-07
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      相关资源
      最近更新 更多