Routes WebApi路由问题-无法路由到所需的操作

Routes WebApi路由问题-无法路由到所需的操作,routes,asp.net-web-api2,Routes,Asp.net Web Api2,我使用了这里选择的答案:构建我的路线,但它们没有按预期工作: 我的路线: config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}", defaults: new { controller = "Products" } ); 我的行动: public string GetProductById(int i

我使用了这里选择的答案:构建我的路线,但它们没有按预期工作:

我的路线:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}",
            defaults: new { controller = "Products" }
        );
我的行动:

public string GetProductById(int id) {}
public string GetProductByIsbn(string isbn) {}
我正试图通过以下方式拨打这些电话:

localhost:60819/api/products/id=33 //doesn't work
localhost:60819/api/products/33 //does work

这两个不起作用的错误相同:

<Error><Message>The request is invalid.</Message>
    <MessageDetail>
        The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String GetProductById(Int32)' in 'BB_WebApi.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
    </MessageDetail>
</Error>
请求无效。
参数字典包含“BB_WebApi.Controllers.ProductsController”中方法“System.String GetProductById(Int32)”的不可为null类型“System.Int32”的参数“id”的null条目。可选参数必须是引用类型、可为null的类型或声明为可选参数。
似乎认为身份证没有被传进来


我已经阅读了所有的msdn文档,但我似乎遗漏了一些东西。有人知道我哪里出错了吗?

您有几个错误(并且您没有显示所有相关代码,或者您显示了错误的代码,如下所述,与路线模板中的
id
相关)

这是行不通的。如果要在URL中传递命名参数,则必须使用查询字符串,即,您需要使用
?id=33
,而不是
/id=33

localhost:60819/api/products/33 //does work
按照你展示的路线,这是行不通的。只有在路由模板中定义参数时,才能将参数作为URL段传递。您的路由模板应该如下所示:
api/{controller}/{id}
,这样就可以从url中恢复
id
,而第二个url确实有效

http://localhost:60819/api/products/isbn=9781408845240 
和第二个一样。使用
?isbn=9781408845240

http://localhost:60819/api/products/testString
这只会将
testString
映射到路由模板中的参数。您需要这样的东西:
isbn=textString
才能调用您感兴趣的操作

因此,请记住:

  • 必须使用正确的查询字符串语法在url查询字符串中传递命名参数,即:
    ?param1=val1¶m2=val2
  • 路由模板中必须存在url段参数。如果没有,活页夹根本不可能对它们做任何事情
由于您似乎缺少很多信息,请阅读以下文档:


这对您来说也很有趣:,它允许您使用路由属性,这比路由模板灵活得多。

谢谢,您是对的,这个示例不起作用,我有另一个路由:
routeTemplate:
允许它工作,因为它有两个参数,但它们都是可选的,因此显然会起作用!。使用问题和
http://localhost:60819/api/products?isbn=9781408845240
我得到一个错误
没有为此对象定义无参数构造函数。
我假设它引用了我的ProductsController???,除非您正在实现自定义控制器激活器(例如,因为您包含了DI框架bottstrapper,比如)控制器激活器需要无参数构造函数来创建控制器实例。
http://localhost:60819/api/products/isbn=9781408845240 
http://localhost:60819/api/products/testString