locked
Getting BadRequest (400) when sending post request by HttpClient C# RRS feed

  • Question

  • User1470230834 posted

    Post Sending Code:

    try       
    {                    
    var json = JsonConvert.SerializeObject(this.Current);                    
    Console.WriteLine(json);                    
    StringContent sc = new StringContent(json, Encoding.UTF8,"application/json");                                     
    
    var post = await this.client.PostAsync("api/customers", sc);                        
    if (post.IsSuccessStatusCode)                        {                            
    Uri lol = post.Headers.Location;                          
     var newcust = await this.client.GetAsync(lol);                            
    if (newcust.IsSuccessStatusCode)                            {                             
       var custData = await newcust.Content.ReadAsStringAsync();                                
    this.CopyCustomer(JsonConvert.DeserializeObject<Custumer>(custData),this.Current);                           
         this.OnPropertyChanged(nameof(Current));            
    }

    Controller Post:

    [ResponseType(typeof(Customer))]
            public async Task<IHttpActionResult> PostCustomer(Customer customer)
            {
    
    
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
                customer.ModifiedDate = DateTime.Now;
                customer.rowguid = Guid.NewGuid();
                db.Customer.Add(customer);
    
                try
                {
                    await db.SaveChangesAsync();
                }
                catch (DbUpdateException)
                {
                    if (CustomerExists(customer.CustID))
                    {
                        return Content(HttpStatusCode.Conflict, $"The customer with id {customer.CustID} are existing. Please add with other id");
                    }
                    else
                    {
                        throw;
                    }
                }
    
    
    
                return CreatedAtRoute("DefaultApi", new { id = customer.CustID }, customer);
            }

    Please, Help me with this problem.

    Best Regards,

    Mammedli Elnur

    Sunday, June 3, 2018 8:04 PM

All replies

  • User36583972 posted


    Hi VisualCoder,

    VisualCoder

    Getting BadRequest (400) when sending post request by HttpClient C#

    When you make a breakpoint in the PostCustomer method. Does it occur? And which code cause this error? Please give us a detailed description.

    I have made a test on my side. It is working.

    Post Sending Code:

        try
                {
                    Customer cus = new Customer() { ID = "12", name = "LUYH" };
    
                    using (var client = new System.Net.Http.HttpClient())
                    {
                        var uri = new Uri("http://localhost:29679/api/TestTwo");
                        string contents = JsonConvert.SerializeObject(cus);
                        var response = client.PostAsync(uri, new StringContent(contents, Encoding.UTF8, "application/json"));
                        response.Wait();
                        if (response.Result.IsSuccessStatusCode)
                        {
                            Uri lol = response.Result.Headers.Location;
                            var newcust = await client.GetAsync(lol);
                            if (newcust.IsSuccessStatusCode)
                            {
                                var custData = await newcust.Content.ReadAsStringAsync();
                                Response.Write(custData);
                            }
                        }
    
                    }
                }
                catch (Exception ex) { }
    

    Controller Post:

            [HttpPost]
            [AllowAnonymous]
            [ResponseType(typeof(Customer))]
            public  IHttpActionResult PostCustomer([FromBody]Customer customer)
            {
                return Ok(customer);
            }

    Besides, If you have many HttpPost methods. You can Routing by Action Name.

    Best Regards,

    Yong Lu

    Monday, June 4, 2018 8:48 AM
  • User1470230834 posted

    Hi, dear Johannn Lu, Thanks for help, but your variant is not working. I do it by changing [FromBody] attribute to [FromUri] and changing uri in post and put. Please, say me why is creating by [FromBody] it's not working at me.

    Best Regards,

    VisualCoder.

    Tuesday, June 5, 2018 4:38 AM
  • User36583972 posted


    Hi VisualCoder,

    but your variant is not working. I do it by changing [FromBody] attribute to [FromUri] and changing uri in post and put. Please, say me why is creating by [FromBody] it's not working at me.

    According to the current information. We can not find out the specific reasons of this issue.

    And have you tried F12 Nework, F12 Console? I'm trying to suggest that rather than stopping at seeing that "it doesn't work", it should be easier to fix the issue if you look at what actually happens (F12 console for possible error messages, F12 network to inspect the http query and the response).

    Please use the F12 tools and give us a detailed description.

    If you have many HttpPost methods. You can Routing by Action Name. Do you tried this on your side?

    Best Regards,

    Yong Lu

    Monday, June 11, 2018 2:43 AM