如何使HttpClient.PostAsync与Postman的发布方式相同?

时间:2019-04-30 18:28:25

标签: c# .net httpclient

当我从Postman发布到我的API(以.NET Core编写并托管在Linux上)时,一切正常。当我从代码(使用HttpClient)执行相同操作时,不会发送参数。在我的代码下面:

let sortedDist = distributors.sort(function(a, b){ 

    let aDist = getDistance(44.3617171302915, -79.65860486970848, a.lat, a.long, "K");
    let bDist = getDistance(44.3617171302915, -79.65860486970848, b.lat, b.long, "K");

    return aDist - bDist;
})

我认为应该发送内容,并且应该一切正常。我发现Wireshark中的调用之间存在显着差异。

Postman的工作POST: Working POST from Postman 来自HttpClient的POST无法正常工作: POST from HttpClient that does not work

如何确保我的HttpClient.PostAsync正确发送数据?

1 个答案:

答案 0 :(得分:2)

Postman版本没有正文,但它在网址中编码有userNameserialNumber作为查询参数。

为了使用HttpClient实现相同的功能,您需要将这些参数添加到url中。

var uriBuilder = new UriBuilder(_uri);

// If you already have query parameters, this code will preserve them. 
// Otherwise you can just create a new NameValueCollection instance.
var parameters = HttpUtility.ParseQueryString(uriBuilder.Query);
parameters[nameof(userName)] = userName;
parameters[nameof(serialNumber)] = serialNumber;

uriBuilder.Query = parameters.ToString();

// Pass null as HttpContent to make HttpClient send an empty body
var result = await _httpClient.PostAsync(uriBuilder.ToString(), null).ConfigureAwait(false);