locked
.net core mvc update call API with httpclientfactory RRS feed

  • Question

  • User-544325736 posted

    Hello all

    I have been able to call my api with Create, Get, GetAll, and Delete. But I am having troubles with only Update. I thought it would be the same as Create but It seems not. I tried with HttpPut and HttpPost but nether called my API method.

    My API is a separate project than my UI. I am eventually going to be using a GateWay making it into a microservice.
    Currently I call my client.SendAsync(httpRequest);
    and it does not reach my API method at all, It does not call the API but all the other CRUD methods call it and works perfectly.
    I get a 400 bad request and 404 not found.

    // Here is my MVC View Controller that calls the API.
    public async Task<IActionResult> UpdateAppUser(string guid)
            {
                AppUser user = new AppUser();
                HttpRequestMessage httprequest = new HttpRequestMessage(HttpMethod.Post, $"https://localhost:5001/api/account/GetUserByID/{guid}");
                // httprequest.Content = new StringContent(guid);
    
                var client = apiClient.CreateClient();
                var response = await client.SendAsync(httprequest);
    
                if (response.IsSuccessStatusCode)
                {
                    var responseString = await response.Content.ReadAsStringAsync();
                    user = JsonConvert.DeserializeObject<AppUser>(responseString);
                   // return View("AppUser", user);
                }/**/
    
    
                return View(user);
            }
            //[Bind("FirstName,LastName,Email")]
            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> UpdateAppUser(AppUser user)
            {
                if (ModelState.IsValid)
                {
                    RegisterModel registerModel = new RegisterModel
                    {
                        Username = user.userName,
                        FirstName = user.firstName,
                        LastName = user.lastName,
                        DateCreated = user.dateCreated,
    
                    };
                    //var model = JsonConvert.SerializeObject(user);
                    var model = JsonConvert.SerializeObject(registerModel);
    
                    HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, $"https://localhost:5001/api/account/UpdateUser/");
                    httpRequest.Content = new StringContent(model, Encoding.UTF8, "application/json");
    
                    var client = apiClient.CreateClient();
                    var response = await client.SendAsync(httpRequest);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        return View("AppUserIndex");
                    }
                }
                return View(user);
            }
    // Here is the API
    [HttpPost("UpdateUser")]
            //[Route("UpdateUser")]
            public async Task<IActionResult> UpdateUser(RegisterModel registerModel)
            {
                if (ModelState.IsValid)
                {
                    var user = await userManager.FindByEmailAsync(registerModel.Email);
                    if (user != null)
                    {
                        user.Email = registerModel.Email;
                        user.UserName = registerModel.Username;
                        user.FirstName = registerModel.FirstName;
                        user.LastName = registerModel.LastName;
    
                        IdentityResult validEmail = null;
                        if (!string.IsNullOrEmpty(registerModel.Email))
                        {
                          //  validEmail = await 
                        }
    
                        IdentityResult identityResult = await userManager.UpdateAsync(user);
                        if (identityResult.Succeeded)
                        {
                            return Ok();
                        }
                    }
                    else
                        return NotFound();
                }
                return BadRequest();
            }

    Sunday, December 27, 2020 3:35 PM

Answers

  • User-544325736 posted

    When I use PostMan or Swagger my Update API call works and updates the data.

    Making sure I have the correct port and uri it gets 'BadRequest 400'

    I am currently not using a gateway I am using a MVC UI to call my API Project. Everything works Except Update.

    Looking at this some more, I am thinking it could be something with the page possibly itself..

    I switched my  form from UpdateUser to CreateUser and it calls the CreateUser action then when I call my httprequest for CreateUser it gets 'BadRequest 400' but when I do create User on my Create page it works with the 200 success.

    I found the issue!!!

    It looks like you CaNNOT convert object types.

    I was inserting AppUser in the view. and the API method took RegisterUser.

    In the mvc method i would convert appuser to registeruser and pass it in.

    that was my bad request.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 28, 2020 8:57 PM

All replies

  • User1312693872 posted

    Hi,ExceedingLife

    I tried with HttpPut and HttpPost but nether called my API method.

    • Make sure the port is correct and it can find the action correctly.
    HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, $"https://localhost:44306/account/UpdateUser/");
    • I tested these code without the 'gateway' and they works well, so the problem may lies on it, you should check whether your gateway can work well

    I get a 400 bad request and 404 not found.

    Could you please tell us about their scenes?

    • 400 bad request  often caused by the bad request, means the request can not access the action.
    • 404 error often means can not find the url.

    You can set break point to check whether you have these mistakes.

    Best Regards,

    Jerry Cai

    Monday, December 28, 2020 9:33 AM
  • User-544325736 posted

    When I use PostMan or Swagger my Update API call works and updates the data.

    Making sure I have the correct port and uri it gets 'BadRequest 400'

    I am currently not using a gateway I am using a MVC UI to call my API Project. Everything works Except Update.

    Looking at this some more, I am thinking it could be something with the page possibly itself..

    I switched my  form from UpdateUser to CreateUser and it calls the CreateUser action then when I call my httprequest for CreateUser it gets 'BadRequest 400' but when I do create User on my Create page it works with the 200 success.

    I found the issue!!!

    It looks like you CaNNOT convert object types.

    I was inserting AppUser in the view. and the API method took RegisterUser.

    In the mvc method i would convert appuser to registeruser and pass it in.

    that was my bad request.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 28, 2020 8:57 PM