[英]Bad Request accessing Web API from Xamarin.Forms
在这里,我解释了我的情况-我有2个项目-API (存储Web API)和APP (存储Xamarin.Forms)。 我已经使用EDMX从我的数据库中的API.Models文件夹中的API项目中创建数据模型。 我想从APP项目访问API,因此在我的APP项目中创建了类似的数据模型类。 当模型类中没有外键时,一切正常。 一旦将外键添加到API项目中的任何模型类中,使用API就会给我带来“错误请求错误”
API.Models代码
namespace API.Models
{
using System;
using System.Collections.Generic;
public partial class Lead
{
public int ID { get; set; }
public string LeadName { get; set; }
public Nullable<decimal> AssignedTo { get; set; }
public virtual User User1 { get; set; } //User is another entity in API.Models
}
}
APP。型号代码
namespace APP.Models
{
using System;
using System.Collections.Generic;
public partial class Lead
{
public int ID { get; set; }
public string LeadName { get; set; }
public Nullable<decimal> AssignedTo { get; set; }
public virtual User User1 { get; set; } //User is another entity in APP.Models
}
}
API代码
namespace APIProject.API
{
public class IssueLogController : ApiController
{
CRMEntities db = new CRMEntities();
[ResponseType(typeof(Lead))]
public async Task<IHttpActionResult> PostLead(Lead lead)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Lead.Add(lead);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (LeadExists(lead.ID))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = lead.ID }, lead);
}
}
}
Xamarin.Forms代码
Lead lead = new Lead();
lead.LeadName = txtLead.Text.Trim();
var uri = Constants.URL + "Lead/PostLead/";
HttpClient client = new HttpClient(new NativeMessageHandler());
var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
var json = JsonConvert.SerializeObject(lead, s);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
await DisplayAlert("Message", "Your Lead has been recorded.", "OK");
}
有解决这个问题的想法吗?
正如@Gerald在上面的评论中提到的,这是我在API代码中所做的操作以找出错误-
if (!ModelState.IsValid)
{
StringBuilder sb = new StringBuilder();
foreach (var state in ModelState)
{
foreach (var error in state.Value.Errors)
{
sb.AppendLine(error.ErrorMessage);
}
}
t_app_issueLog.ID = 1;
t_app_issueLog.Problem = sb.ToString();
return CreatedAtRoute("DefaultApi", new { id = lead.ID }, lead);
//return BadRequest(ModelState);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.