gpt4 book ai didi

asp.net-web-api - 将 ViewModel 传递给 Web-Api 操作

转载 作者:行者123 更新时间:2023-12-02 08:44:11 25 4
gpt4 key购买 nike

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

而不是使用:

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 Controller 中使用 ModelState.IsValid。

最佳答案

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

public IEnumerable<Contact> GetContacts([FromUri]TestVM testVM)
{
// some logic
}

关于asp.net-web-api - 将 ViewModel 传递给 Web-Api 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13723722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com