0

I'm having a hard time executing a http get call with headers to an api with oauth2 authorization.

I already tried the code below but then I'm receiving an Unauthorized response from the api. I think the problem is that because I've executed the GETASYNC() without the adding some headers. Can you help me to find a way on how to add headers before I execute the GETASYNC().

public HttpClient webApiClient = new HttpClient();

public async System.Threading.Tasks.Task<ActionResult> Index()
{
    var uri = new Uri("https://myURL.com/"+ transno);

    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    var response = await webApiClient.GetAsync(uri);

    response.Headers.Add("Accept", "application/json");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    response.Headers.Add("client-id", "clientid");
    response.Headers.Add("client-secret", "clientsecret");
    response.Headers.Add("partner-id", "partnerid");   

    var result = JObject.Parse(await response.Content.ReadAsStringAsync());
}
ikey
  • 321
  • 4
  • 19
  • I'm not familiar with WebApiClient. Is that a custom class you made? Or is it from some particular library? – mason May 02 '19 at 01:32
  • ```public HttpClient WebApiClient = new HttpClient();``` Here is the WebAPIClient reference sorry for the confustion – ikey May 02 '19 at 01:45
  • 1
    In C#, it's standard convention to name local variables in `camelCase`. Also, keep in mind that anyone reading your question isn't going to be familiar with your code base. So it's up to you to show enough in your example that an outside can grasp it. All that said, I haven't done much work with OAuth 2 and HttpClient. But it appears you're adding headers to the response, when you should be adding them to your request instead. Meaning before your `WebApiClient.GetAsync()` call. – mason May 02 '19 at 01:49
  • 1
    If you need an example of adding headers to an HttpClient request, see [this question](https://stackoverflow.com/questions/35907642/custom-header-to-httpclient-request/35910012). However, I highly reccomend you look into using [Flurl](https://flurl.dev/docs/fluent-http/) instead. It makes it easier to build your request URL, add headers, and parse responses, and avoids some common mistakes made with HttpClient. – mason May 02 '19 at 01:58
  • I'm sorry for the incorrect naming and insufficient block of code that I've shown. Thanks also for informing me about the standard naming conventions I'll apply that practice to my coding this time. Thank you for your help. – ikey May 02 '19 at 02:01

0 Answers0