在C#中使用基本身份验证调用WEB API [英] Calling WEB API with basic authentication in C#

查看:217
本文介绍了在C#中使用基本身份验证调用WEB API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个有效的WEB API,并且向该API添加了基本身份验证(用户名是"testing",密码是"123456").但是,当尝试从我的Web表单调用该API时,我总是收到(401)未经授权"消息.要成功调用API,我应该在网络代码中进行哪些更改?

I have a working WEB API that I wrote, and I added basic authentication to the API (username is "testing", password is "123456"). However, when trying to call that API from my web form, I keep getting the "(401) Unauthorized" message. What should I change in the web code to call the API successfully?

 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();
 }

这是我的API根据身份验证搜索的内容:

This is what my API searches for in terms of authentication:

actionContext.Request.Headers.Authorization.Parameter

我应该添加标题而不是NetworkCredential还是同一回事?

Should I be adding a header instead of NetworkCredential or is it the same thing?

推荐答案

这应该有所帮助:

    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();
    }

这篇关于在C#中使用基本身份验证调用WEB API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆