Search code examples
c#asp.net-coreroutescontrollerhttpclient

httpcilent PostAsJsonAsync return null in model


I am using an HTTP endpoint HttpClient to send request to my controller like that:

var uri = new Uri("http://localhost:5075/Agent/ChangeAgent");
 
            var model = new ChangeAgentRequestViewModel
            {
                Address = "test",
                AgentType = 1,

            };
            var response = await _httpClient.PostAsJsonAsync (uri, model);

So in my controller I get model:

 public async Task<IActionResult> ChangeAgent(ChangeAgentRequestViewModel model)
        {

            var res = await _agentService.SaveAgent(model);
            return Json(res);
        }

I expect this model contain AgentType or Address but value for both is 0 and null. When I am changing my request input as [FromBody] it is going to work, but because it is call by another endpoint I don't want to change my controller like public async Task<IActionResult> ChangeAgent([FromBody]ChangeAgentRequestViewModel model) . so is there any method that give me that values in httpclient ?


Solution

  • Firstly, you need know that PostAsJsonAsync sends a POST request to the specified Uri containing the value serialized as JSON in the request body.

    Then [FromBody] means the api requires application/json content type data, but you said if you do not specify the source by [FromBody], it will not receive value. That is to say the request api need data posted from form.

    So if you do not want to specify the [FromBody] attribute, you need send data like below:

    var data = new Dictionary<string, string>
    {
        {"Address", "test"},
        {"AgentType", "1"}
    };
    
    var response = await _httpClient.PostAsync(uri, new FormUrlEncodedContent(data));