Hello all
How to call update API with httpclientfactory in asp.net core mvc
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.
// 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.Get, $"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();
}