0
我正在嘗試更新類「Conversation」中的變量,將參數對象由於某種原因而未綁定。我不知道爲什麼不。結果我收到此錯誤:在Web Api中執行PUT時的NullObjectReference
"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);
}
Model類用戶:
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; }
}
}
模型類的對話:
[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; }
}
我在郵差這樣的測試此:
ROUTE = api/Conversations/AddMember/?key="1LM4"
JSON = {"user": { "Email": "[email protected]", "Password" : "Passw-1", "Admin" : true } }