asp.net-mvc - 从网站到外部 Web api 的简单 POST 失败

标签 asp.net-mvc azure

我有一个 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/

相关文章:

mysql - 缺少模板中的 Visual Studio 2013 数据库

asp.net-mvc - 单元测试期间的 Mvcontrib.MVC3.Testhelper UpdateModel NullReferenceExceuption

c# - 从 Azure Servicebus/IotHub 接收消息

c# - 我应该使用 BlobContainerClient 还是 BlobClient 还是两者都使用?

ASP.NET MVC NuGet Glimpse 删除 - HTTP_COOKIE 中仍列出 Glimpse 引用

c# - 如何从 xamrin webview 调用同一台机器上的你自己的 ASP.NET MVC 项目

asp.net-mvc - 在 Web 层之外获取当前的 Principal

azure - 如何在失败时保持 Azure 服务总线消息队列处理?

php - 即使没有任何用户,Microsoft Azure Linux VM 每天 24 小时始终具有较高的 CPU 使用率

azure - 自动缩放器存储客户端错误