locked
Getting 400 on Put/Update Method Asp.net core webapi RRS feed

  • Question

  • User2041008840 posted

    Hello,

    I am getting error while updating record through asp.net core webapi. I am using Blazor Wasm and calling data through webapi asp.net core
    I also tried this in postman but still showing 400 error status code

    {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"Bad Request","status":400,"traceId":"|824703b9-4d672e5b7644d22c."}

    what is the exact issue ? 

    Tuesday, August 11, 2020 4:49 PM

All replies

  • User475983607 posted

    Prathamesh Shende

    Hello,

    I am getting error while updating record through asp.net core webapi. I am using Blazor Wasm and calling data through webapi asp.net core
    I also tried this in postman but still showing 400 error status code

    {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"Bad Request","status":400,"traceId":"|824703b9-4d672e5b7644d22c."}

    what is the exact issue ? 

    A 400 (bad request) status means the client code has bugs.  Usually a problem with the post data format or HTTP message. Try reviewing your code for correctness and using standard debug tools to find the problem with your code.   

    Share the code if you want a community code review.  It is best if you share code the community can actually run which takes a bit of effort on your part.  Help us to help you.

    Tuesday, August 11, 2020 5:02 PM
  • User2041008840 posted

    controller

    [HttpPut("{id}")]
          public async Task<IActionResult> PutStock(int id, Stock stock)
          {
              if (id != stock.ID)
              {
                  return BadRequest();
              }
     
              _context.Entry(stock).State = EntityState.Modified;
     
              try
              {
                  await _context.SaveChangesAsync();
              }
              catch (DbUpdateConcurrencyException)
              {
                  if (!StockExists(id))
                  {
                      return NotFound();
                  }
                  else
                  {
                      throw;
                  }
              }
     
              return NoContent();
          }
        

    blazor wasm 

    public async Task<HttpResponseMessage> UpdateStockAsync(int id, Stock Stock)
           {
               var client = new HttpClient();
               return await client.PutAsync($"{apiUrl.BaseUrl}api/Stocks/{id}", GetStringContentFromObject(Stock));
           }
     
            private StringContent GetStringContentFromObject(object obj)
           {
               var serialized = JsonConvert.SerializeObject(obj);
               var stringContent = new StringContent(serialized, Encoding.UTF8, "application/json");
               return stringContent;
           }
    
    Tuesday, August 11, 2020 5:08 PM
  • User475983607 posted

    The code is incomplete and you ignored my request to provide code the community could simply run.  Sad...

    Anyway, you code specifically returns a 400 (Bad Request) if the id and stock.ID are not the same.  Have tried running your code through the debugger to verify what's happening?  

    I created a test and it works fine.  Here's my test code.

    [Route("api/[controller]")]
    [ApiController]
    public class StockController : ControllerBase
    {
        private readonly ILogger<StockController> _logger;
        public StockController(ILogger<StockController> logger)
        {
            _logger = logger;
        }
    
        [HttpGet]
        public async Task<IActionResult> GetStock()
        {
            return Ok(new Stock() { ID = 1 });
        }
    
        [HttpPut("{id}")]
        public async Task<IActionResult> PutStock(int id, Stock stock)
        {
            _logger.LogInformation($"id = {id} and stockID = {stock.ID}.");
    
            if (id != stock.ID)
            {
                return BadRequest();
            }
    
            return NoContent();
        }
    }
    
    public class Stock
    {
        public int ID { get; set; }
    }
    @page "/HttpClientDemo"
    @inject HttpClient Http
    
    <h3>HttpClientDemo</h3>
    <hr />
    <div>
        Status Code = @statusCode.ToString()
    </div>
    
    @code {
        private Stock stock;
        private System.Net.HttpStatusCode statusCode;
    
        protected override async Task OnInitializedAsync()
        {
            //stock = await Http.GetFromJsonAsync<Stock>("https://localhost:44379/api/stock");
            Stock stock = new Stock() { ID = 1 };
    
            var results = await Http.PutAsync("https://localhost:44379/api/stock/1",
                new StringContent(
                    System.Text.Json.JsonSerializer.Serialize(stock),
                    System.Text.Encoding.UTF8,
                    "application/json"));
    
            statusCode = results.StatusCode;
        }
    
    
    
        public class Stock
        {
            public int ID { get; set; }
        }
    
    }
    

    Tuesday, August 11, 2020 6:07 PM