为什么HttpClient.PostAsJson发送Get请求

时间:2017-09-12 14:46:44

标签: c# post get asp.net-core-webapi

下面一行

        HttpResponseMessage response = await _httpClient.PostAsJsonAsync(resource, request);

被调用, HttpClient正在向端点发送GET请求(通过fiddler确认),即使调用的方法是PostAsJsonAsync。如果我调用PostAsync或PostAsJson,它也会这样做。

这会导致失败,因为我调用的WebApi端点只接受帖子而不是获取。 有谁知道为什么会发生这种情况?

我在下面使用的课程:

public class LaneRestClient : IDisposable
{
    private readonly HttpClient _httpClient;

    public LaneRestClient(IOptions<LaneApiConfigurationOptions> laneApiOptions)
    {
        var laneApiConfigurationOptions = laneApiOptions.Value;
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri(laneApiConfigurationOptions.LaneApiUrl);
        _httpClient.DefaultRequestHeaders.Accept.Clear();
        var byteArray = new UTF8Encoding().GetBytes($"{laneApiConfigurationOptions.LaneApiUsername}:{laneApiConfigurationOptions.LaneApiPassword}");
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
        _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));

    }

    public async Task<TResultType> Post<TResultType, TRequestType>(string resource, TRequestType request)
    {
        HttpResponseMessage response = await _httpClient.PostAsJsonAsync(resource, request);

        if (!response.IsSuccessStatusCode)
        {
            throw new HttpRequestException("Lane Api Request Failed: " + response.StatusCode + " - " +
                                           response.ReasonPhrase);
        }

        string resultJsonString = await response.Content.ReadAsStringAsync();

        var result = JsonConvert.DeserializeObject<TResultType>(resultJsonString);
        return result;

    }

}

这是使用.NET标准API客户端库,由.NET Core 2.0 Web应用程序调用并调用.NET Framework WebAPI2(如果相关)。

0 个答案:

没有答案