简体   繁体   English

MVC使用登录凭据访问外部Web API

[英]MVC accessing external Web API using login credentials

In need of some help accessing an external Web API passing along credentials in order to access the methods available. 在访问外部Web API以及传递凭据时需要一些帮助,以访问可用的方法。 I have included the code below that i use in order to attempt to access the Web API. 我已经包含了下面用来尝试访问Web API的代码。 However, i receive the following error every time i attempt to access it: 但是,每次尝试访问它时,我都会收到以下错误:

"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." “基础连接已关闭:无法为SSL / TLS安全通道建立信任关系。”

What am i missing or what am i doing wrong? 我想念什么或我做错了什么? I have been circling around this for a couple days and have tried a couple different techniques but continue to get the same error. 我已经绕了几天,并尝试了几种不同的技术,但仍然遇到相同的错误。 Here is one technique that i used. 这是我使用的一种技术。

 private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
    {
        try
        {
            using (var client = new HttpClient())
            {
                //setup client
                client.BaseAddress = new Uri(apiBaseUri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //setup login data
                var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string,string>("username",userName),
                new KeyValuePair<string,string>("password",password),
            });

                //send request
                HttpResponseMessage responseMessage = await client.PostAsync("Token", formContent);

                //get access token from response body
                var responseJson = await responseMessage.Content.ReadAsStringAsync();
                var jobject = JObject.Parse(responseJson);
                return jobject.GetValue("access_token").ToString();
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks 谢谢

There is a little bit of a difference when using HTTPS vs HTTP. 使用HTTPS和HTTP时有一些区别。 This question should give you the information you need to fix your problem. 该问题应为您提供解决问题所需的信息。

Make Https call using HttpClient 使用HttpClient进行Https调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM