0

At the risk of asking a noob question, I am trying to test a url to post to a webapi endpoint that it should have model bound to, were this MVC:

    public ReturnModel GetSomeInformation( ValidationPackage validationPackage)
    {
        return new ReturnModel();
    }

where ValidationPackage is something like:

public class ValidationPackage : BaseValidationPackage
{
    [DataMember]
    public int ClubId { get; set; }
}

So when I simply try to test this or demo it for my iOS guy that needs it, the following doesn't bind:

http://[local]/api/meet/GetInformation?ClubId=152

Should I change the method signature to this, then it all works fine:

public ReturnModel GetSomeInformation( int clubId) {...}

But somehow I was under the impression that my first version should have worked and that I'm doing something wrong as I was under the impression that webapi was just an implementation of MVC.

4

2 回答 2

1

stringMVC(和 Web API)简单类型( 、、、int等)中模型绑定的默认行为Guid是从查询字符串绑定的。另一方面,对象将使用请求的主体进行绑定。FromBodyAttribute您可以使用或FromUriAttribute(取决于您的需要)在每个参数的基础上更改此行为:

public ReturnModel GetSomeInformation([FromUri]ValidationPackage validationPackage)
{
    return new ReturnModel();
}
于 2013-08-05T14:28:21.790 回答
1

默认情况下,Web API 会将查询字符串参数绑定到原始类型,并将请求正文内容绑定到复杂类型

模型绑定器ValidationPackage在请求正文中需要一个对象,但您在查询字符串中传递了一个原语。

您可以将以下内容作为您的帖子正文:

{
  "ClubId": 152
}

如果您需要在查询字符串中传递它,您需要使用[FromUri]属性覆盖默认行为:

public ReturnModel GetSomeInformation([FromUri] ValidationPackage validationPackage)
{
    return new ReturnModel();
}

这里有更多关于 Web Api 的参数绑定功能的信息,你可以这里找到一个类似的问题。

于 2013-08-05T14:29:00.073 回答