Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GitHub API access with Personal Access Token using C# HttpClient and .NET Core
public class Program
{
public static void Main(string[] args)
{
Task.WaitAll(ExecuteAsync());
Console.ReadLine();
}
public static async Task ExecuteAsync()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.github.com");
var token = "<token>";
client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("AppName", "1.0"));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", token);
var response = await client.GetAsync("/user");
}
}
@MaximRouiller

This comment has been minimized.

Copy link
Owner Author

@MaximRouiller MaximRouiller commented Aug 14, 2018

This is the bare minimum to access the app. You could probably remove the "Accept" and rely on the default.

Authorization and User-Agent are required.

@darrelmiller

This comment has been minimized.

Copy link

@darrelmiller darrelmiller commented Aug 14, 2018

Dude! User-Agent should always be added to, not overwritten.

client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("appName"));
@MaximRouiller

This comment has been minimized.

Copy link
Owner Author

@MaximRouiller MaximRouiller commented Aug 15, 2018

Okay, will modify tomorrow to do this right.

In this case, doesn't matter... But I agree with you

@MaximRouiller

This comment has been minimized.

Copy link
Owner Author

@MaximRouiller MaximRouiller commented Aug 15, 2018

@darrelmiller happy? 😄

@AnthonyDGreen

This comment has been minimized.

Copy link

@AnthonyDGreen AnthonyDGreen commented Mar 8, 2019

Thanks! This helped me with a demo I was putting together!

@LawrenceMcKellar

This comment has been minimized.

Copy link

@LawrenceMcKellar LawrenceMcKellar commented Jun 3, 2020

Thanks :-)

@stefanrothnet

This comment has been minimized.

Copy link

@stefanrothnet stefanrothnet commented Jun 16, 2021

Awesome thanks, just needed this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment