Home > Software engineering >  Getting null Model from PostAsync Request
Getting null Model from PostAsync Request

Time:04-20

I am making a communication between two microservices. I am trying to obtain the content from the model "UserBookPreference". I already debugged and the content that is being sent in the PostAsync() request is correct (let's say, data from microservice A). The problem arises when I try to receive the contents from the Post method in microservice B. The model type I have as parameter is the same I am sending from the postAsync. Since I am using .NET 5, the JsonContent.Create() method is a good approach according to my reasearch. I have tried other methodologies, such as using the StringContent() method but still I get the null object in microservice B. This is the code I am using. In microservice A:

 public async Task<string> AddFavoriteBook(UserBookPreference bookModel)
        {
            JsonContent content = JsonContent.Create(bookModel);
            var response = await httpClient.PostAsync(URLHelper._baseUserPreferencesMicroserviceURL   "/Book", content);
            var responseString = await response.Content.ReadAsStringAsync();
            return responseString;
}

In microservice B:

[HttpPost("Favorites/Book")]
        public IActionResult AddUserFavoriteBook(UserBookPreference bookModel)
        {
            try
            {
                _prefService.AddUserBookFavorite(bookModel);
                return Ok(bookModel);
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }

Thank you for your time.

CodePudding user response:

You need to either add [FromBody] attribute before UserBookPreference in your endpoint or add a [ApiController] attribute to your controller to bind UserBookPreference to incoming body. docks

  • Related