Xamarin PostAsync不提供内容响应

kq4fsx7k  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(124)

我在Xamarin表单中执行此功能:

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;
    }
}

此代码函数返回无内容,即使赋值后。任何线索,我错了。WebAPI是工作正常的POSTMAN。我的WebAPI控制器看起来像这样:

[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;
    }
}

帮帮忙。谢谢

7qhs6swi

7qhs6swi1#

解决了。

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);

将Encoding.UTF8替换为UnicodeEncoding.UTF8,成功了,谜团解开了。

相关问题