0

在 WCF Web API Preview 5 上,我正在处理一个奇怪的行为。这是场景:

这是我的模型:

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
}

这是 API:

[ServiceContract]
public class PersonApi {

    [WebGet(UriTemplate = "person?id={ID}&name={Name}&surname={Surname}&age={Age}")]
    public Person Get(Person person) {

        return person;
    }

}

我使用以下代码注册了 API:

RouteTable.Routes.MapServiceRoute<ADummy.PersonApi>("Dummy");

当我运行尝试使用以下 URL 访问服务时,我收到此错误:

localhost:36973/Dummy/person?id=1&name=Tugberk&surname=Ugurlu&age=24


服务操作“Get”永远不会收到“Person”类型的输入参数“person”的值。确保请求 HttpOperationHandler 具有可分配给“Person”类型的输出参数。

但是当我像下面这样更改我的 API 逻辑时,它可以工作:

[ServiceContract]
public class PersonApi {

    [WebGet(UriTemplate = "person?id={ID}&name={Name}&surname={Surname}&age={Age}")]
    public Person Get(int ID, string Name, string Surname, int Age) {

        var p = new Person { 
            ID = ID,
            Name = Name,
            Surname = Surname,
            Age = Age
        };

        return p;
    }

}

在 WCF Web API 中,我想事情不像在 ASP.NET MVC 中那样工作。

什么是模型绑定到 WCF Web API 中的对象的方式?

更新

我添加了另一种方法:

[WebInvoke(UriTemplate= "put", Method="POST")]
public Person Put(Person person) {

    return person;
}

当我使用以下详细信息调用此方法时:

方法:POST

网址:http://localhost:36973/Dummy/put

接受:/ Content-Type:text/xml

内容长度:189

身体:

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ID>1</ID>
<Name>Tugberk</Name>
<Surname>Ugurlu</Surname>
<Age>25</Age>
</Person>

我得到了我需要的东西。那么,查询字符串绑定到自定义对象是不允许的吗?

4

2 回答 2

0

根据您的经验,设计行为似乎是 Get() 操作只会绑定 UriTemplate 中定义的参数。就目的和安全性而言,这是正确的行为。

于 2011-11-23T13:06:50.947 回答
0

最新版本的ASP.NET Web API(随 ASP.NET MVC 4 Beta 发布)支持模型绑定。

模型绑定和验证:模型绑定器提供了一种从 HTTP 请求的各个部分提取数据并将这些消息部分转换为 Web API 操作可以使用的 .NET 对象的简单方法。

对于以前版本的 ASP.NET Web API,可以使用 HttpOperationHandler 实现所需的功能,并在 OnHandle 方法中返回模型。也许验证模型属性 WCF Web APi问题和答案可用于启发。

于 2012-02-21T12:51:40.163 回答