【问题标题】:WebApi Routing issue - unable to route to required actionWebApi 路由问题 - 无法路由到所需的操作
【发布时间】:2015-08-14 18:43:33
【问题描述】:

我已使用此处选择的答案:Routing based on query string parameter name 来构建我的路线,但它们没有按预期工作:

我的路线:

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

和

http://localhost:60819/api/products/isbn=9781408845240 //doesn't work
http://localhost:60819/api/products/testString //test with a definite string - doesn't work - still tries to use GetProductById(int id)

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

<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>

似乎认为 id 没有被传入...?

我已经阅读了所有的 msdn 文档,但我似乎在某处遗漏了一些东西。谁能看出我哪里出错了?

【问题讨论】:

    标签: routes asp.net-web-api2


    【解决方案1】:

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

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

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

    localhost:60819/api/products/33 //does work
    

    对于您显示的路线,这是行不通的。只有在路由模板中定义这些参数时,才能将参数作为 URL 段传递。你的路由模板应该是这样的:api/{controller}/{id} 这样id 可以从 url 中恢复,第二个 URL 确实有效。

    http://localhost:60819/api/products/isbn=9781408845240 
    

    与第二个相同。使用?isbn=9781408845240

    http://localhost:60819/api/products/testString
    

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

    所以,记住这一点:

    • 命名参数必须在url查询字符串中传递,使用正确的查询字符串语法,即:?param1=val1&amp;param2=val2
    • url 段参数必须存在于路由模板中。如果没有,活页夹就不可能对它们做任何事情。

    您似乎遗漏了很多信息,请阅读以下文档:Parameter Binding in ASP.NET Web API。

    这对您来说也可能很有趣:Attribute Routing in ASP.NET Web API 2,它允许您使用路由属性,这比路由模板灵活得多。

    【讨论】:

    • 谢谢,你是对的,那个例子不起作用,我有另一条路线:routeTemplate: "api/{controller}/{id}/{anotherid}", 允许它工作 - 我不认为它有 2 个参数,但是它们都是可选的,所以它显然可以工作!使用问题中的路线和http://localhost:60819/api/products?isbn=9781408845240 我得到错误No parameterless constructor defined for this object. 我假设是指我的ProductsController???
    • 除非您正在实现自定义控制器激活器(例如,因为您包含 DI 框架bottstrapper,如stackoverflow.com/questions/13018417/…),否则控制器激活器需要无参数构造函数来创建控制器实例。跨度>
    猜你喜欢
    • 1970-01-01
    • 2013-07-03
    • 2018-04-05
    • 2018-07-07
    • 2016-02-03
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多