将ViewModel传递给Web-Api操作

fil*_*lip 2 asp.net-web-api

是否可以将ViewModel对象传递给WebApi控制器操作而不是单独的参数?

而不是使用:

public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetContacts(string p1, string p2)
    {
        // some logic
    }
}
Run Code Online (Sandbox Code Playgroud)

我想用:

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; }
}
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎不起作用.当我调用/ api/contacts /?P1 = aaa&P2 = bbb时,testVM对象不会被填充(null).

另外,我希望TestVM定义了valdiation属性,并在我的API控制器中使用ModelState.IsValid.

Mar*_*nes 6

除非另有说明,否则WebApi将使用请求的内容/正文对复杂模型进行反序列化.要告诉WebApi使用Url构建模型,您需要指定[FromUri]属性:

public IEnumerable<Contact> GetContacts([FromUri]TestVM testVM)
{
    // some logic
}
Run Code Online (Sandbox Code Playgroud)