我从另一个项目(C#类)调用webApi,其中一个属性始终为null。我在调试时验证了对象是否已正确填充。正在传递的对象存储在两个项目中引用的共享库中。所以不应该是类型不匹配。
我在帖子发送之前验证了order.Products.Answers已设置。然后我在WebApi方法中有一个断点,它的null。我不确定为什么。
以下是用于生成帖子的代码:
[HttpPost]
public ActionResult Add(ApiOrder order)
{
try
{
HttpResponseMessage resp = null;
ApiOrder processedOrder = null;
using (var client = new HttpClient())
{
var url = GetUrlToWebApis();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Task<HttpResponseMessage> task = client.PostAsJsonAsync("apisecure/order", order);
//resolve the reque
resp = task.Result;
var a = resp.Content.ReadAsAsync<ApiOrder>();
processedOrder = a.Result;
TempData["ConfirmMessage"] = "Order Was added";
}
return View("Add", processedOrder);
}
catch (Exception e)
{
//ViewBag.messgae = e.InnerException;
TempData["ErrorMessage"] = e.InnerException;
return View("Add", order);
}
}
这是处理Post
的WebApi方法public IHttpActionResult Post(ApiOrder order)
这里是ApiOrder的类结构
[DataContract]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class ApiOrder
{
[DataMember]
[Required]
public virtual int Id { get; set; }
[DataMember]
// [Required]
public virtual List<ApiProduct> Products { get; set; }
}
现在是ApiProduct类
[DataContract]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class ApiProduct
{
[DataMember]
[Required]
public virtual int ActionId { get; set; }
[DataMember]
public virtual List<ApiAnswer> Answers { get; set; } // <-- Always null
}
最后是ApiAnswer
[DataContract]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class ApiAnswer
{
[DataMember]
[Required]
public virtual int QuestionId { get; set; }
[DataMember]
public virtual string QuestionText { get; set; }
[DataMember]
public virtual string Answer { get; set; }
}
答案 0 :(得分:1)
AHHHHH, 问题是我有两个解决方案,其中一个箱子有一个过时的dll。清理和重建两种解决方案解决了这个问题。