c# - 尝试 POST 到 RESTful 服务时尝试 webRequest.GetRequestStream 时发生 System.Net.WebException

标签 c# rest httpwebrequest webrequest

当我输入与我的 dot net 4.0 应用程序中使用的相同的值和设置时,针对 chrome 的 Advanced REST Client 使用值工作正常。

另一方面,当我尝试使用来自 dotnet 的客户端 REST 服务时,当我调用 webRequest.GetRequestStream() 时我的应用程序立即崩溃,但出现异常 {"The underlying connection was closed: An unexpected error occurred on a send 。”},HREsult -2146233079,内部异常“”身份验证失败,因为远程方已关闭传输流。“HResult -2146232800 这是我的代码,但我更改了一些值以保护我客户的详细信息。

当代码尝试 getrequeststream() 时,我的 fiddler 监视器会生成 2 个条目以显示我的应用程序正在联系服务器。它不应该只是创建一个带有授权 header 和 json 内容的整个数据包并在一次调用中发送它吗?或者这是 POST 通常的工作方式? Fiddler 从不从 chrome 的 ARC 中获取事件,所以我无法比较。

我已经尝试过 WebRequest、webclient、httpwebrequest 等,但都无法正常工作。 (我不能使用新的 webclient 类,因为我的主要应用程序是 dotnet 4.0)。我以管理员模式运行 VS。 chrome 的 Advanced REST 客户端如何工作,而我的不行?有什么区别?

string parsed = @"    {
  "data": {
    "workoutDate": "2015-01-23",
    "exerciseType": "TREADMILL",
    "workoutDuration": 1456,
    "distance": 1382.0,
    "energyConsumed": 567068.0,
    "averageHeartRate": 75.0,
    "averageSpeed": 1.0
  },
  "user": {
    "email": "bumbly.boms@pdd.com",
    "firstName": "Len",
    "lastName": "BlTestoomers",
    "gender": "MALE",
    "dateOfBirth": "1984-10-27"
  }
}";
  // Add authorization headers
  string authentication = string.Format("Authorization: RRgym SNUFFCENTRE:{0}:gymId246", EyupSecurityKey.GenerateAuthenticationKey());

  // Convert the parsed string into byte[]
  byte[] buffer = Encoding.UTF8.GetBytes(parsed);

  string addr = "https://equipment.test.pogram.uk/acr-rest/equipment/v1/workout/endurance";

  WebRequest webRequest = WebRequest.Create(addr);
  webRequest.Method = WebRequestMethods.Http.Post;
  webRequest.ContentType = "application/json";
  webRequest.ContentLength = buffer.Length;
  webRequest.Headers.Add(authentication);

  Stream newStream = webRequest.GetRequestStream();
  // Send the data.
  newStream.Write(buffer, 0, buffer.Length);
  newStream.Close();

}

最佳答案

我会发布这个来帮助其他可能有同样问题的人。

客户联系我说我的问题可能是因为他们的服务器设置的安全级别高于基础 visual studio。 (Chrome ARC 一定可以正常处理)。

所以我不得不设置 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 就在创建我的网络请求之前。

不幸的是,该协议(protocol)在 dotnet4.0 中不受支持,但在 4.5 中支持,因此我需要提出一个修复方案。但那是另一天:)

关于c# - 尝试 POST 到 RESTful 服务时尝试 webRequest.GetRequestStream 时发生 System.Net.WebException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28433776/

相关文章:

c# - Mono:非 SSL URI 上的 HttpWebRequest SSL 错误

c# - LLBLGen : How can I softdelete a entry

javascript - angularjs资源查询误解数组

java - JSON 中的 WebApplicationException 使用

java - 带有投影的JAVA中的OData REST API

xcode - 快速网络请求未提交(使用alamofire)

c# - .NET 中 DataTable 或其他复杂对象的最大大小

c# - Visual Studio 2019 v16.6无法构建.net5控制台应用程序并引发错误: . NETFramework,Version = v5.0未找到

c# - 在字符串类型textBox中设置int值

asp.net - AJAX post 中的 HttpWebRequest 之后 session 状态丢失