c# - 使用 C# HttpClient API 和 postman 测试的区别?客户端调用适用于 postman ,但不适用于 C# httpClient getAsync

标签 c# rest api httpclient postman

Enter image description here

Enter image description here

我正在测试 REST API 帖子,当我在 Postman 上尝试时它运行良好。但是,在某些情况下(与发布 XML 数据相关)如果我使用 HttpClient API 发布,我会收到以下错误:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

但相同的 XML 内容在 Postman 上运行良好,状态正常且响应正确。

使用C# HttpClient API和postman测试有什么区别?如何配置我的 API 调用以匹配 postman 的行为?

这里附上源码和Postman截图

public void createLoan()
{
    string baseCreateLoanUrl = @"https://serverhost/create?key=";
    var strUCDExport = XDocument.Load(@"C:\CreateLoan_testcase.xml");

    using (var client = new HttpClient())
    {
        var content = new StringContent(strUCDExport.ToString(), Encoding.UTF8, Mediatype);
        string createLoanApi = string.Concat(baseCreateLoanUrl, APIKey);

        try
        {
            var response = client.PostAsync(createLoanApi, content).Result;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error Happened here...");
            throw;
        }

        if (response.IsSuccessStatusCode)
        {
            // Access variables from the returned JSON object
            string responseString = response.Content.ReadAsStringAsync().Result;
            JObject jObj = JObject.Parse(responseString);

            if (jObj.SelectToken("failure") == null)
            {
                // First get the authToken
                string LoanID = jObj["loanStatus"]["id"].ToString();
                MessageBox.Show("Loan ID: " + LoanID);
            }
            else
            {
                string getTokenErrorMsg = string.Empty;

                JArray errorOjbs = (JArray) jObj["failure"]["errors"];
                foreach (var errorObj in errorOjbs)
                {
                    getTokenErrorMsg += errorObj["message"].ToString() + Environment.NewLine;
                }
                getTokenErrorMsg.Dump();
            }
        }
    }

最佳答案

感谢 Nard 的评论,在比较 header 后,我发现我的客户端 header 存在以下问题: 期望:100-继续

而 postman 没有。

一旦我使用 ServicePointManager 删除了它:

ServicePointManager.Expect100Continue = false;

现在一切似乎都很好。感谢所有的输入!

关于c# - 使用 C# HttpClient API 和 postman 测试的区别?客户端调用适用于 postman ,但不适用于 C# httpClient getAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41129203/

相关文章:

c# - 仅将线程用于 Web 服务调用,而不用于 Db 调用

c# - 运算符(operator) ?。和扩展方法

node.js - 无法读取未定义的属性“错误”。有什么问题?

xml - 有没有办法为亚马逊的产品获取 XML?

python - 如何在 Python 中格式化 JSON 文本?

javascript - 如何使用 spotify web api 获取用户的播放列表列表?

c# - 如何以编程方式保存 Beyond Compare 生成的比较报告

java - JSON 响应中属性的自己的特定名称

java - JAVA中的Microsoft Office 365邮件REST API

c# - ConstantExpression 不是常量