0

I am doing this function in Xamarin Forms:

public async Task<HttpResponseMessage> RegisterClient(string url)
{
    try
    {
        using (HttpClient httpclient1 = new HttpClient())
        {
            var newClient = new Client()
            {
                CountryId = 223,
                Email = "somename@123.com",
                Fname = "From Xamarin",
                UserName = "somename",
                Dob = Convert.ToDateTime("2020-01-01"),
                Password = "SomeSome"               
            };

            var jsonObject = JsonConvert.SerializeObject(newClient);
            HttpContent content = new StringContent(jsonObject, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await httpclient1.PostAsync(url, content);
            return response;
        }
    }
    catch (Exception ex)
    {
        await DisplayAlert("Information", ex.Message, "Ok");
        return null;
    }
}

This code function is returning No Content even after assigning values. Any clue where i am wrong. WebAPI is working fine in POSTMAN. My WebAPI Controller looks like this:

[HttpPost("PostClient")]
public async Task<ActionResult<Client>> PostClient(Client client)
{
    try
    {
        _context.Clients.Add(client);
        await _context.SaveChangesAsync();
        return CreatedAtAction("GetClient", new { id = client.ClientId }, client);
    }
    catch(Exception ex)
    {
        return null;
    }
}

Please help. Thank you

Jugnu Khan
  • 63
  • 3
  • 9

1 Answers1

0

Resolved.

HttpClient httpClient = new HttpClient();
Uri uri = new Uri(url);
StringContent content = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, content);
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
Console.WriteLine(httpResponseBody);

Replaced Encoding.UTF8 to UnicodeEncoding.UTF8 and it worked. Mystery solved.

Jugnu Khan
  • 63
  • 3
  • 9