简体   繁体   English

C#.. API httpclient身份验证和具有用户名和密码的代理

[英]C# .. API httpclient authentication and proxy with username and password

I'm new in API's world but I had a question, I want to get data from Web API but there's two authentication 我是API世界的新手,但是我有一个问题,我想从Web API获取数据,但是有两种身份验证

  • First with proxy. 首先与代理。
  • Second with API base authentication. 其次是基于API的身份验证。

here's my Get Action code: 这是我的“获取操作”代码:

        HttpClientHandler handler = new HttpClientHandler();
        handler.Credentials = new NetworkCredential("test", "testing");
        HttpClient client = new HttpClient(handler);
        client.BaseAddress = new Uri("http://test.abctesting.com/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.
            MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
        var tenders = response.Content.ReadAsAsync<tenders>().Result;

this code work fine with me but just in pass over proxy username and password! 此代码对我来说很好用,但只是通过代理用户名和密码传递! How can I continue to Get API Data with authentication username and password? 如何继续使用身份验证用户名和密码获取API数据?

This should work: 这应该工作:

HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("test", "testing");
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://test.abctesting.com/");
client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(
    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

string user = "user", password = "password";

string userAndPasswordToken =
    Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + password));

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", 
    $"Basic {userAndPasswordToken}");

HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
var tenders = response.Content.ReadAsAsync<tenders>().Result;

Since you mentioned "Basic Auth" on comments adding the following lines in addition to what you have might help 由于您在评论中提到了“基本身份验证” ,因此除了添加以下内容外,还可能会有所帮助

 var byteArray = Encoding.ASCII.GetBytes($"{yourUsername}:{yourPassword}");
 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

Although there are other popular modes of auth such as OAuth , Bearer etc. Change the key on AuthenticationHeaderValue according to the mode of authentication and set the value appropriately 尽管还有其他流行的auth模式,例如OAuthBearer等。请根据AuthenticationHeaderValue模式更改AuthenticationHeaderValue上的密钥并适当设置值

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

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