在Controller中调用需要身份验证的API

时间:2016-12-22 23:33:18

标签: c# asp.net api asp.net-web-api

我正在创建调用第三方API的ASP.NET。只能提供用户名和密码才能访问第三方API。

   public string Get(string LabName)
    {
        string userName = ConfigurationManager.AppSettings["username"];
        string password = ConfigurationManager.AppSettings["password"];
        string BaseURL = ConfigurationManager.AppSettings["BaseURL"];

        using (var client = new HttpClient())
        {

            Uri uri = new Uri(BaseURL);
            client.BaseAddress = uri;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
            string clarity_URL = BaseURL+"api/v2/labs?name="+LabName;
            var response = client.GetAsync(clarity_URL).Result;

            string responseString = response.Content.ReadAsStringAsync().Result;
            return responseString;

我不确定如何在ASP.NET中调用API时传递用户名和密码。任何人都建议我如何安全地调用API

1 个答案:

答案 0 :(得分:0)

 client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password")));