How to use credentials in HttpClient in c#?

蓝咒 提交于 2019-11-27 23:29:31
Adam Szabo

I had the exact same problem myself. It seems the HttpClient just disregards the credentials set in the HttpClientHandler.

The following shall work however:

using System.Net.Http.Headers; // For AuthenticationHeaderValue

const string uri = "https://example.com/path?params=1";
using (var client = new HttpClient()) {
    var byteArray = Encoding.ASCII.GetBytes("MyUSER:MyPASS");
    var header = new AuthenticationHeaderValue(
               "Basic", Convert.ToBase64String(byteArray));
    client.DefaultRequestHeaders.Authorization = header;

    var result = await client.GetStringAsync(uri);
}

No need for the handler.

Source: http://www.snip2code.com/Snippet/13895/Simple-C---NET-4-5-HTTPClient-Request-Us

This is an old post but thought to add my reply for someone facing similar issue and browsing answers...

I faced similar issue. In my case, setting Domain property for NetworkCredentials worked. You can try setting Domain.

The code you are showing works for me against an authenticated resource. I suspect Delicious is doing something weird.

Considering you are on Windows Phone, it is a pain to debug with Fiddler, so what I suggest is getting a Runscope account. Install this message handler which will redirect your request via the RunScope debugger. Once you do this, I suggest you look at the www-authenticate header and examine what that is returning.

If all else fails you can always set the Authentication header directly with basic auth credentials. You don't need to use the Credentials class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!