Xamarin连接Https与POST,asp.net-web-api-2,“身份验证或解密失败”

时间:2017-02-14 10:49:09

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

我是初学者,我使用一个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);

Postman示例,对于此连接,我得到一个连接令牌:

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)时,据说不要创建连接whit线程UI,而是使用另一个线程。 但是我发现的很多例子都没有使用线程UI,为什么呢? 或者我误解了一件事?

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

或许我只是完全迷失了......(哈哈)。

祝你好运, 罗曼

1 个答案:

答案 0 :(得分:0)

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

System.Security.Cryptography.AesCryptoServiceProvider AES = new System.Security.Cryptography.AesCryptoServiceProvider();

System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;

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