使用 httpclient 使用 Json Body 调用 Get 请求

Ron*_*hia 4 c# httpclient xamarin xamarin.forms .net-core

今天早上我遇到了一个问题,我调用的 Api 是一个 Get 方法,但要从中获取数据,我必须发送 json 正文,当我在邮递员中测试它时,这工作得很好,但我没有能够在我的项目中实现它,我使用 HttpClient 调用它

这是帖子的截图

在此输入图像描述

它还有一个我在授权中传递的不记名令牌

现在,当我尝试在客户端实现此操作时,这是我的代码

  var stringPayload = JsonConvert.SerializeObject(json);
        var client = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri("https://myapiendpoint/serviceability/"),
            Content = new StringContent(stringPayload, Encoding.UTF8, "application/json"),
        };
        var response = await client.SendAsync(request).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

当我使用此代码调用此方法时,我得到

System.Net.HttpStatusCode.MethodNotAllowed - Status code 405
Run Code Online (Sandbox Code Playgroud)

我也尝试改变这条线

 Method = HttpMethod.Get to Method = HttpMethod.Post
Run Code Online (Sandbox Code Playgroud)

但仍然遇到同样的错误

我知道这是 API 端的糟糕实现,理想情况下请求应该是 POST,但更改此操作不在我手中,因此需要找到解决方案

Ron*_*hia 7

几乎搜索遍了并尝试使用 GET 方法的所有变体最后在这种情况下对我有用的解决方案是这样的

var client = new HttpClient();
            client.BaseAddress = new Uri("https://baseApi/");
            client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", token));
            var query = new Dictionary<string, string>
            {
                ["pickup_postcode"] = 400703,
                ["delivery_postcode"] = 421204,
                ["cod"] = "0",
                ["weight"] = 2,
            };

            var url = "methodurl";
            var response = await client.GetAsync(QueryHelpers.AddQueryString(url, query));
            var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            return JsonConvert.DeserializeObject<MyModel>(responseBody);
Run Code Online (Sandbox Code Playgroud)

从 Microsoft.AspNetCore.WebUtilities 包获取 QueryHelpers