简体   繁体   中英

Bad Request accessing Web API from Xamarin.Forms

Here, I explain my scenario - I have 2 projects - API (storing the Web API) and APP (storing the Xamarin.Forms). I have used EDMX to create Data models from my database in the API project in API.Models folder. I want to access the API from the APP project and hence have created similar data model classes in my APP project. Things work fine when there are no Foreign Keys present in the model class. As soon as a Foreign Key is added to any of the model classes in API project, consuming the API starts giving me a "Bad Request error"

API.Models Code

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.Models Code

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 Code

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 code

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");
        }

Any ideas to resolve this?

As mentioned by @Gerald in comments above, here is what I did in the API code to figure out the error -

 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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM