在Web Api中执行PUT时的NullObjectReference

时间:2016-02-29 18:12:57

标签: asp.net-web-api2 nullreferenceexception http-put

我正在尝试更新类中的变量" Conversation"由于某种原因,参数对象没有绑定。我不知道为什么不。结果我收到了这个错误:

01000011

控制器:

01000011

模型类用户:

"Object reference not set to an instance of an object.",

模特课堂对话:

[HttpPut]
public async Task<IHttpActionResult> AddMember(string key, User user)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    Conversation conver = await db.Conversations.FindAsync(key);     //THIS IS NULL

    if (conver == null)
    {
        return NotFound();      //METHOD IS ENDING HERE
    }

    conver.Members.Add(user);   //THIS IS NULL

    db.Entry(conver).State = EntityState.Modified;
    try
    {
        await db.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        return NotFound();
    }

     return StatusCode(HttpStatusCode.NoContent);
}

我在Postman中测试这个:

ROUTE = namespace AcademicAssistant.Models { [DataContract] public class User { [Key] [DataMember] public string Email { get; set; } [DataMember] public string Password { get; set; } [DataMember] public bool Admin { get; set; } } }

JSON = [DataContract] public class Conversation { [Key] [DataMember] public string Key { get; set; } [DataMember] public string ConversationName { get; set; } [DataMember] public string Administrator { get; set; } [DataMember] public virtual ICollection<User> Members { get; set; } [DataMember] public virtual ICollection<Message> Messages { get; set; } }

1 个答案:

答案 0 :(得分:0)

<强> SOLUTION:

路线应该是

api/Conversations/AddMember/?key=1LM4

和JSON格式如下:

{
    "Email": "56@56.com",
    "Password" : "Passw-1",
    "Admin" : true
}