'How To Pass ErrorMessage From API to MVC In Asp.Net Core

I've created an API. When you face an error, It shows you the type of error with it's message. But When I try to use that API in my MVC project, It just shows the type of error. I want to see the message in Modelstate.AddModelError

Here is API controller for Login

[HttpPost("login")]
        public async Task<IActionResult> LoginUser([FromBody] UserDtoLogin user)
        {
            var userToRetrieve = await _applicationDbContext.Users.FirstOrDefaultAsync(u => u.UserName == user.UserName);
            if (userToRetrieve == null)
            {
                ModelState.AddModelError("username", "Such a user doesn't exists! Enter the correct username please");
                return NotFound(ModelState);
            }
            if (!_userRepository.VerifyPasswordHash(user.Password, userToRetrieve.PasswordHash, userToRetrieve.PasswordSalt))
            {
                ModelState.AddModelError("password", "Wrong Password!");
                return BadRequest(ModelState);
            }
            await _userRepository.Login(userToRetrieve);
            return Ok(user);
        }

Here is MVC Controller for Login

[HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:42045/api/user/login");
            if (user != null)
            {
                request.Content = new StringContent(JsonConvert.SerializeObject(user),
                    System.Text.Encoding.UTF8, "application/json");
            }
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                ViewBag.StatusCode = System.Net.HttpStatusCode.OK;
                var apiString = await response.Content.ReadAsStringAsync();
                user = JsonConvert.DeserializeObject<User>(apiString);
            }
            else
            {
                ViewBag.StatusCode = response.StatusCode;
            }
            return View(user);

        }


Solution 1:[1]

I write a simple demo to show how to pass ErrorMessage From API to MVC In Asp.Net Core, you can reference to it.

API

    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {

    //For testing convenience, I use hard code here

        List<UserDtoLogin> context = new List<UserDtoLogin>
        {
            new UserDtoLogin
            {
                UserName = "Mike"
            },

            new UserDtoLogin
            {
                UserName = "Jack"
            },

            new UserDtoLogin
            {
                UserName = "Lily"
            }
        };

        [HttpPost("login")]
        public IActionResult LoginUser([FromBody] UserDtoLogin user)
        {
            var userToRetrieve =  context.FirstOrDefault(u => u.UserName == user.UserName);
            if (userToRetrieve == null)
            {
               
                return BadRequest("Such a user doesn't exists! Enter the correct username please");
            }

            //your logic.....

            return Ok();
        }
    }

MVC/Controller

        [HttpPost]
        public async Task<IActionResult> Privacy(UserDtoLogin todoItem)
        {
            var todoItemJson = new StringContent(JsonSerializer.Serialize(todoItem),Encoding.UTF8,Application.Json);

            using var httpResponseMessage = await _httpClient.PostAsync("your api url", todoItemJson);
            var errormessage = httpResponseMessage.Content.ReadAsStringAsync().Result;

            return View(todoItem);
        }

Then you can see it can receive the errormessage successfully.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Xinran Shen