在 C# 中使用基本身份验证调用 WEB API

May*_*erk 9 c# asp.net credentials basic-authentication asp.net-web-api

我有一个我编写的工作 WEB API,我向 API 添加了基本身份验证(用户名是“testing”,密码是“123456”)。但是,当尝试从我的 Web 表单调用该 API 时,我不断收到“(401) Unauthorized”消息。我应该在 Web 代码中更改什么才能成功调用 API?

 string url = String.Format("http://example.com"); //here I have the correct url for my API
 HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);
 requestObj.Method = "Get";
 requestObj.PreAuthenticate = true;
 requestObj.Credentials = new NetworkCredential("testing", "123456");
 HttpWebResponse responseObj = null;
 responseObj = (HttpWebResponse)requestObj.GetResponse();
 string strresult = null;
 using (Stream stream = responseObj.GetResponseStream())
 {
     StreamReader sr = new StreamReader(stream);
     strresult = sr.ReadToEnd();
     sr.Close();
 }
Run Code Online (Sandbox Code Playgroud)

这是我的 API 在身份验证方面搜索的内容:

actionContext.Request.Headers.Authorization.Parameter
Run Code Online (Sandbox Code Playgroud)

我应该添加一个标头而不是 NetworkCredential 还是同样的事情?

小智 15

这应该有帮助:

    HttpMessageHandler handler = new HttpClientHandler()
    {
    };
        
    var httpClient = new HttpClient(handler)
    {
         BaseAddress = new Uri(url),
         Timeout = new TimeSpan(0, 2, 0)
    };
        
    httpClient.DefaultRequestHeaders.Add("ContentType", "application/json");
        
    //This is the key section you were missing    
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("testing:123456");
    string val = System.Convert.ToBase64String(plainTextBytes);
    httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + val);
        
    HttpResponseMessage response = httpClient.GetAsync(url).Result;
    string content = string.Empty;
        
    using (StreamReader stream = new StreamReader(response.Content.ReadAsStreamAsync().Result, System.Text.Encoding.GetEncoding(_encoding)))
    {
         content = stream.ReadToEnd();
    }
Run Code Online (Sandbox Code Playgroud)