【问题标题】:Xamarin connection Https with POST, asp.net-web-api-2, "The authentication or decryption has failed"Xamarin 连接 Https 与 POST,asp.net-web-api-2,“身份验证或解密失败”
【发布时间】:2017-02-14 10:49:08
【问题描述】:

我是初学者,我使用一个 Xamarin 应用程序。 我尝试将我的应用程序连接到一个 Https 服务器以获取令牌,当我测试与 Postman 的连接时,一切正常。但对于我的应用程序,则是另一回事了..

网络服务是:aps.net-web-api-2

这是我在 Xamarin 中的连接代码:

using System.Net.Http;

protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.Main);
        Button button = FindViewById<Button>(Resource.Id.getButton);

        button.Click += async (sender, e) =>
        {
            try
            {
                string url = "https://urlexample/foo/bar/Token";
                string values = await RequestWeb(url);
            }
            catch (Exception ex)
            {
                Log.Info("error with click", ex.ToString());
            }
        };
    }

    private async Task<string> RequestHttps(string url)
    {
        string responseString = string.Empty;

        using (HttpClient client = new HttpClient())
        {
            Dictionary<string,string> values = new Dictionary<string, string>
            {
               { "grant_type", "password" },
               { "username", "User1" },
               { "password", "123456" }
            };

            FormUrlEncodedContent content = new FormUrlEncodedContent(values);
            HttpResponseMessage response = await client.PostAsync(url, content);

            responseString = await response.Content.ReadAsStringAsync();
        }
        return responseString;
    }

当我使用我的代码进行测试时,我使用 Try and Catch 恢复了我的异常:

I/error with click(14476): System.Net.WebException: Error: TrustFailure (The authentication or decryption has failed.)

问题来自这一行:

HttpResponseMessage response = await client.PostAsync(url, content);

以邮递员为例,对于这个连接,我得到一个连接令牌:

Post -> Headers
- Content_type : application/x-www-form-urlencoded
- grand_type : password
- username : User1
- password : 123456

结果:

{ "access_token": "ATT4U2xGQqsdf", "token_type": "bearer", "expires_in": 15 }

我也尝试其他连接方式 (example here) 而且我想知道,当我阅读适用于 Android 的课程 (here) 时,据说不要使用线程 UI 创建连接,而是使用另一个线程。 但是我发现很多例子都没有使用线程 UI,为什么? 还是我误解了一件事?

我也想知道问题是否来自我的设置?

或者也许我完全迷路了......(哈哈)。

最好的问候, 罗曼

【问题讨论】:

    标签: c# android xamarin https asp.net-web-api2


    【解决方案1】:

    请在您的 App.cs 代码中使用InitializeComponent(); 之前的这两行代码。

    System.Security.Cryptography.AesCryptoServiceProvider AES = new System.Security.Cryptography.AesCryptoServiceProvider();
    
    System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
    

    默认情况下,Mono 没有受信任的证书,因此您要么必须跳过错误,要么添加一个证书来补充您的 POST。

    【讨论】:

    • 感谢 Zroq 的回答!它现在运行良好,非常感谢您提供此信息!
    • 如何“添加一个补充您的 POST 的证书”?
    猜你喜欢
    • 2013-04-22
    • 2018-05-09
    • 2011-06-23
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多