JamesS
JamesS

Reputation: 2300

API request is null when using SendAsync

I have a request object below:

public class SearchRequest
{
    [JsonProperty(PropertyName = "search_value")]
    public string Value { get; set; }
}

and a web api endpoint that expects

[HttpPost]
[Route("~/api/city/search")]
public SearchResponse Search(SearchRequest request)
{
    try
    {
        var result = _cityService.Search(request);

        return result;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

which I call using the following

var serialisedRequest = JsonConvert.SerializeObject(request);

which serialises the request like {"search_value":"test"}.

var content = new StringContent(serialisedRequest, Encoding.UTF8, "application/json");

using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
    SetupHttpClient(client);

    var fullUrl = string.Format("{0}/{1}", baseUri, svcEndPoint);


    var request = new HttpRequestMessage { Content = content, Method = HttpMethod.Post, RequestUri = new System.Uri(fullUrl) };

    using (var result = await client.SendAsync(request))
    {
        if (result.IsSuccessStatusCode)
        {
            var content = await result.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResponse>(content);
        }
     }
 }

When I call the API and put a break point in the API controller, the value for Value is null.

Any reason why this would be?

Upvotes: 0

Views: 1449

Answers (1)

vernou
vernou

Reputation: 7590

The attribute Newtonsoft.Json.JsonPropertyAttribute is used by the deserializer json.net.But from ASP.NET Core 3, the default deserializer is System.Text.Json. Then the expected attribute is System.Text.Json.Serialization.JsonPropertyNameAttribut.

In your case :

public class SearchRequest
{
    [JsonPropertyName("search_value")]
    public string Value { get; set; }
}

From @HenkHolterman comment, it seem the class SearchRequest is shared between the client and server. But the client use json.net and the server use System.Text.Json, then you need specify the two attribute like :

public class SearchRequest
{
    // To desierialize on the client by json.net
    [JsonProperty(PropertyName = "search_value")]
    // To desierialize on the server by System.Text.Json
    [JsonPropertyName("search_value")]
    public string Value { get; set; }
}

Other solution I advice, it's to use the same json library on the client and the server.

Upvotes: 2

Related Questions