Your first code block seems a little strange. If the registration fails, you return a success response with the description of the first error. Your client code is going to have to rely on parsing the response content to see whether it's a "successful success" or a "failed success" response, rather than just checking the
IsSuccessStatusCode
property.
According to the documentation, the automatic "bad request" responses for model state errors only happen if your controller or its base class is decorated with the
[ApiController]
attribute:
Create web APIs with ASP.NET Core | Microsoft Learn[
^]
If you're not using that attribute, then you still need to check
ModelState.IsValid
.
The validity of the model state should
always be checked in the API. You should
never trust client input, and for an API, the model is that input. It's safest to always assume there's a team of people trying to break into your system by sending malformed requests. :)
Assuming you fix the response from your API so that it
doesn't return
200 OK
when the registration fails, then I'd be inclined to rewrite your application code slightly:
[HttpPost]
public async Task<IActionResult> Registration([FromForm] RegisterViewModel model)
{
if (ModelState.IsValid)
{
var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
var body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
using (var response = await httpClient.PostAsync("https://localhost:7129/api/Auth/Register?", body))
{
if (response.IsSuccessStatusCode)
{
TempData["RegistrationMessage"] = await response.Content.ReadAsStringAsync();
return RedirectToAction("RegistrationSuccess", "Registration");
}
var problem = await response.Content.ReadFromJsonAsync<HttpValidationProblemDetails>();
ModelState.AddModelError("*", problem.Detail);
if (problem.Errors is not null)
{
foreach (var (propertyName, errors) in problem.Errors)
{
foreach (string error in errors)
{
ModelState.AddModelError(propertyName, error);
}
}
}
}
}
return View();
}
public IActionResult RegistrationSuccess()
{
ViewBag.Message = TempData["RegistrationMessage"];
return View();
}
The register view can then rely on a standard validation summary / validation message to display the errors. The success view can read
ViewBag.Message
to get the "registration succeeded" message to display.