控制器方法无法识别模型参数
本文关键字:模型 参数 识别 方法 控制器 | 更新日期: 2023-09-27 18:25:03
我有一个名为PostUserAccount的模型,我正试图在ApiController中使用它作为参数,就像通常使用实体框架生成具有读/写操作的控制器时一样
控制器生成器生成的示例:
// POST api/Profile
public HttpResponseMessage PostUserProfile(UserProfile userprofile)
{
if (ModelState.IsValid)
{
db.UserProfiles.Add(userprofile);
...etc
我正在使用的代码:
// POST gamer/User?email&password&role
public HttpResponseMessage PostUserAccount(PostAccountModel postaccountmodel)
{
if (!ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
}
if (postaccountmodel == null) return Request.CreateResponse(HttpStatusCode.BadRequest, "model is null");
...etc
无论出于何种原因,在这种情况下,postaccountmodel为null,运行此api命令会返回"model为null"。有什么想法吗?
这是有问题的模型
public class PostAccountModel
{
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public string Role { get; set; }
public string Avatar { get; set; }
public string DisplayName { get; set; }
}
您正试图在URI查询字符串中发送模型。问题:
-
您的查询字符串格式不正确-应该是吗?电子邮件=xxx&密码=xxx&。。
-
您需要用[FromUri]属性修饰postaccountmodel参数,以告诉Web API从URI 绑定模型
另一种选择是将请求主体中的模型作为JSON或XML发送。我建议你这样做,尤其是如果你真的在请求中发送了密码。(并使用SSL!)
本主题介绍Web API中的参数绑定:http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
尝试将[FromBody]属性放在postaccountmodel参数前面。
http://msdn.microsoft.com/en-us/library/system.web.http.frombodyattribute(v=vs.108).aspx