[英]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.