Answers for "consume api in c#"

C#
0

c# consuming post rest service

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers; 

namespace ConsoleProgram
{
    public class DataObject
    {
        public string Name { get; set; }
    }

    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json";
        private string urlParameters = "?api_key=123";

        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body.
                var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
                foreach (var d in dataObjects)
                {
                    Console.WriteLine("{0}", d.Name);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            //Make any other calls using HttpClient here.

            //Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
            client.Dispose();
        }
    }
}
Posted by: Guest on October-21-2020
0

Consume Api in Mvc C#

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using app.Models;
using Newtonsoft.Json;

namespace app.Services
{
  public class SimpleApiService : IApiService
  {
    private HttpClient client = new HttpClient();
    private readonly ITokenService tokenService;
    public SimpleApiService(ITokenService tokenService)
    {
      this.tokenService = tokenService;
    }

    public async Task<IList<string>> GetValues()
    {
      List<string> values = new List<string>();
      var token = tokenService.GetToken();
      client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
      var res = await client.GetAsync("http://localhost:5000/api/values");
      if(res.IsSuccessStatusCode)
      {
        var json = res.Content.ReadAsStringAsync().Result;
        values = JsonConvert.DeserializeObject<List<string>>(json);
      }
      else
      {
        values = new List<string>{res.StatusCode.ToString(), res.ReasonPhrase};
      }
      return values;
    }
  }
}
Posted by: Guest on September-16-2021

Code answers related to "consume api in c#"

C# Answers by Framework

Browse Popular Code Answers by Language