[英]Getting null Model from PostAsync Request
I am making a communication between two microservices.我正在两个微服务之间进行通信。 I am trying to obtain the content from the model "UserBookPreference".我正在尝试从 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).我已经调试过并且在PostAsync()
请求中发送的内容是正确的(比方说,来自微服务 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.当我尝试从微服务 B 中的 Post 方法接收内容时出现问题。我作为参数的 model 类型与我从 postAsync 发送的类型相同。 Since I am using .NET 5, the JsonContent.Create()
method is a good approach according to my reasearch.由于我使用的是 .NET 5,根据我的研究, JsonContent.Create()
方法是一种很好的方法。 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.我尝试了其他方法,例如使用StringContent()
方法,但我仍然在微服务 B 中得到 null object。这是我正在使用的代码。 In microservice A:在微服务 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:在微服务 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.感谢您的时间。
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.您需要在端点中的UserBookPreference
之前添加[FromBody]
属性,或者将 [ApiController [ApiController]
属性添加到您的 controller 以将UserBookPreference
绑定到传入的正文。 docks 码头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.