模型参数无法通过控制器方法识别

时间:2013-07-26 22:25:42

标签: c# asp.net-mvc-4 asp.net-web-api

我有一个名为PostUserAccount的模型,我尝试在ApiController中使用它作为参数,就像使用Entity Framework

生成具有读/写操作的控制器时的方式一样

控制器生成器生成的示例:

    // 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; }
}

2 个答案:

答案 0 :(得分:2)

您正尝试在URI查询字符串中发送模型。问题:

  1. 您的查询字符串格式不正确 - 应该是?Email = xxx& Password = xxx& ...

  2. 您需要使用[FromUri]属性修饰postaccountmodel参数,以告知Web API从URI绑定模型

  3. 另一种选择是将请求体中的模型作为JSON或XML发送。我建议,特别是如果你真的在请求中发送密码。 (并使用SSL!)

    本主题介绍Web API中的参数绑定:http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

答案 1 :(得分:-1)

尝试将[FromBody]属性放在postaccountmodel参数前面。

http://msdn.microsoft.com/en-us/library/system.web.http.frombodyattribute(v=vs.108).aspx

相关问题