我有两个模型:-
public class Builder
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int BuilderId { get; set; }
public string BuilderName { get; set; }
}
public class Project
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProjectId { get; set; }
[Required]
public string ProjectName { get; set; }
[Required]
public string Location { get; set; }
[Required]
public int BuilderId { get; set; }
public Builder builder { get; set; }
}
当我尝试将构建器类对象从客户端发布到 web api 方法时,它正在从正文中读取对象。没有问题。但是当我尝试使用一些 Builder 添加任何项目时,它不会调用所需的方法。和我的网络方法:-
public HttpResponseMessage PostProject([FromUri] Project project)
{
if (ModelState.IsValid)
{
db.Projects.Add(project);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, project);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = project.ProjectId }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
我调用 web api 方法的方法:-
public async Task<ActionResult> Create(Project projects)
{
try
{
HttpClient client = new HttpClient();
JavaScriptSerializer serializer = new JavaScriptSerializer();
String contentStr = serializer.Serialize(projects);
ObjectContent content = new ObjectContent(typeof(Project), projects, new JsonMediaTypeFormatter());
HttpResponseMessage putResponse = await client.PostAsync(serviceprovider + "project/postproject", content);
putResponse.EnsureSuccessStatusCode();
return RedirectToAction("Index");
}
catch (HttpRequestException e)
{
return View();
}
}
据我所知,我认为这会造成问题,因为我的对象很复杂。我是 Web API 的新手,欢迎您提出任何建议。请帮忙。