是否可以将ViewModel对象传递给WebApi控制器操作而不是单独的参数?
代替使用:
public class ContactsController : ApiController
{
public IEnumerable<Contact> GetContacts(string p1, string p2)
{
// some logic
}
}
我想使用:
public class ContactsController : ApiController
{
public IEnumerable<Contact> GetContacts(TestVM testVM)
{
// some logic
}
}
public class TestVM
{
public string P1 { get; set; }
public string P2 { get; set; }
}
这似乎对我不起作用。当我调用/ api / contacts /?P1 = aaa&P2 = bbb时,不会填充testVM对象(空)。
此外,我希望TestVM具有定义的属性,并在我的API控制器中使用ModelState.IsValid。
除非另有说明,否则WebApi将使用请求的内容/正文反序列化复杂模型。要告诉WebApi使用Url来构建模型,您需要指定[FromUri]属性:
public IEnumerable<Contact> GetContacts([FromUri]TestVM testVM)
{
// some logic
}
我知道发布另一个答案有点晚了,但我认为对于使用.net core作为Web API服务的任何人都可能有用