ASP.. NET Web API 2模型未绑定
本文关键字:模型 绑定 API NET Web ASP | 更新日期: 2023-09-27 17:49:21
我使用的是VS 2013和ASP。. NET Web API 2用于iOS应用程序的后端。一切都很顺利,直到我尝试使用Web API 2实现我的第一个POST。我使用MVC Web API 1构建了一个以前的API,实现POST没有问题。使用[FromBody]属性应该工作,但我的"请求"总是空的。该模型不具有约束力。有人能看出我的错误或者给我一些帮助吗?
UsrDTO
public class UsrDTO
{
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public int companyId { get; set; }
public bool isManager { get; set; }
public bool isAdmin { get; set; }
}
Usr控制器
[RoutePrefix("api/usr")]
public class UsrController : BaseAPIController
{
[Route("")]
public HttpResponseMessage Post([FromBody]UsrDTO request)
{
var ctx = repo.GetContext();
Usr user = new Usr();
user.Id = new Guid(userId);
user.Username = request.email;
user.FirstName = request.firstName;
user.MiddleName = request.middleName;
user.LastName = request.lastName;
user.Email = request.email;
user.CompanyId = request.companyId;
user.IsManager = request.isManager;
user.IsAdmin = request.isAdmin;
user.IsActive = true;
user.CreatedOn = DateTime.Now;
ctx.Usr.Add(user);
ctx.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, user);
}
}
提琴手请求
POST http://localhost:49763/api/usr HTTP/1.1
User-Agent: Fiddler
Host: localhost:49763
Content-Length: 230
Content-Type: application/json; charset=utf-8
{
"firstName" : "test",
"middleName" : "test",
"lastName":"test",
"email": "test@test.com",
"companyId" = 1,
"isManager"=false,
"isAdmin"=false
}
啊,我的json请求正文中出现了错别字。现在工作。