我有一个 asp .net MVC 页面
我正在尝试连接到 Eventbrite:s api
简单地说,它要求您将客户端 ID 发送到一个网址,使用 HttpGET 和 HttpPOST 将结果和更多信息发送到另一个网址。
GET 进展顺利,我得到了所需的(验证)“代码”。当我尝试将 POST 发送到第二个网址时,我得到
"Socket Exception: An existing connection was forcibly closed by the remote host"
我可以使用 Postman POST 到第二个网址来自 GET 请求的信息工作正常,我得到了身份验证 token 。
这是我使用的代码
var parameters = new Dictionary<string,string>();
parameters.Add("code", pCode);
parameters.Add("client_secret", CLIENT_SECRET);
parameters.Add("client_id", CLIENT_APP_KEY);
parameters.Add("grant_type", "authorization_code");
using (var client = new HttpClient())
{
var req = new HttpRequestMessage(HttpMethod.Post, pUrl) { Content = new FormUrlEncodedContent(parameters) };
var response = client.SendAsync(req).Result;
return response.Content.ReadAsStringAsync().Result;
}
我模糊记得发布到 Azure 时遇到过类似的问题。由于我必须使用公共(public)返回 url 注册我的应用程序,因此我无法使用 fiddler 查看请求。
我的网站正在运行 https。 我还测试了添加以下行(来自一些谷歌搜索)
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
但随后我收到 404 错误...
我也测试过这个(结果相同)
using (var client = new HttpClient())
{
var response = client.PostAsync(pUrl, content).Result;
authToken = response.Content.ReadAsStringAsync().Result;
}
我测试过获取授权码并从本地计算机运行 POST,结果相同...
我已联系 eventbrite 开发人员支持,看看他们是否也可以帮助我...
最佳答案
This POST must contain the following urlencoded data, along with a Content-type:
application/x-www-form-urlencoded
header.
由于您的内容类型是 application/x-www-form-urlencoded
,因此您需要对 POST 正文进行编码,尤其是当它包含 &
等字符时在形式上具有特殊的含义。
然后使用以下函数来发布您的数据:
using (var httpClient = new HttpClient())
{
using (var content = new FormUrlEncodedContent(parameters))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
return await response.Content.ReadAsAsync<TResult>();
}
}
您提供的错误信息表示远端关闭了连接,原因是:
·您正在向应用程序发送格式错误的数据。
·由于某种原因,客户端和服务器之间的网络链接断开。
·您在第三方应用程序中触发了一个错误,导致其崩溃。
·第三方应用程序已耗尽系统资源。
·设置ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol |安全协议(protocol)类型.Tls11 | SecurityProtocolType.Tls12;
更多详情可以引用这个case .
关于asp.net-mvc - 从网站到外部 Web api 的简单 POST 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51132055/