【发布时间】:2012-01-04 17:37:08
【问题描述】:
在 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 有一个输出参数,其类型可分配给 '人'。
但是当我像下面这样更改我的 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
接受:/ 内容类型: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>
我得到了我需要的东西。那么,查询字符串绑定到自定义对象是不允许的吗?
【问题讨论】:
-
如果将操作从 Get() 更改为 Post(),是否会正确绑定 Person 模型?
-
@counsellorben 查看我的更新。
标签: asp.net-mvc wcf asp.net-mvc-3 wcf-web-api