We help IT Professionals succeed at work.

How to connect the restful api through c#

High Priority
207 Views
Last Modified: 2019-05-24
Hi Experts,
I need a help to write the code in C#
how to connect the restful api in the C# code.
I have the restful url and credentials.

Can you please share me the sample code .

Regards,
Praveen
Comment
Watch Question

CEO Faru Bonon IT /Top Rated Freelancer on Upwork / Photographer
CERTIFIED EXPERT
Awarded 2018
Distinguished Expert 2018
Commented:
from
https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace HttpClientSample
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }

    class Program
    {
        static HttpClient client = new HttpClient();

        static void ShowProduct(Product product)
        {
            Console.WriteLine($"Name: {product.Name}\tPrice: " +
                $"{product.Price}\tCategory: {product.Category}");
        }

        static async Task<Uri> CreateProductAsync(Product product)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync(
                "api/products", product);
            response.EnsureSuccessStatusCode();

            // return URI of the created resource.
            return response.Headers.Location;
        }

        static async Task<Product> GetProductAsync(string path)
        {
            Product product = null;
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.IsSuccessStatusCode)
            {
                product = await response.Content.ReadAsAsync<Product>();
            }
            return product;
        }

        static async Task<Product> UpdateProductAsync(Product product)
        {
            HttpResponseMessage response = await client.PutAsJsonAsync(
                $"api/products/{product.Id}", product);
            response.EnsureSuccessStatusCode();

            // Deserialize the updated product from the response body.
            product = await response.Content.ReadAsAsync<Product>();
            return product;
        }

        static async Task<HttpStatusCode> DeleteProductAsync(string id)
        {
            HttpResponseMessage response = await client.DeleteAsync(
                $"api/products/{id}");
            return response.StatusCode;
        }

        static void Main()
        {
            RunAsync().GetAwaiter().GetResult();
        }

        static async Task RunAsync()
        {
            // Update port # in the following line.
            client.BaseAddress = new Uri("http://localhost:64195/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                // Create a new product
                Product product = new Product
                {
                    Name = "Gizmo",
                    Price = 100,
                    Category = "Widgets"
                };

                var url = await CreateProductAsync(product);
                Console.WriteLine($"Created at {url}");

                // Get the product
                product = await GetProductAsync(url.PathAndQuery);
                ShowProduct(product);

                // Update the product
                Console.WriteLine("Updating price...");
                product.Price = 80;
                await UpdateProductAsync(product);

                // Get the updated product
                product = await GetProductAsync(url.PathAndQuery);
                ShowProduct(product);

                // Delete the product
                var statusCode = await DeleteProductAsync(product.Id);
                Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
    }
}

Open in new window

Kyle AbrahamsSenior .Net Developer
CERTIFIED EXPERT
Commented:
This is how I do my Web API calls.  


 private static void setTLS()
        {
            //use TLS 1.2, Ignore cert errors.
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;//| (SecurityProtocolType)768 ;

          ServicePointManager.ServerCertificateValidationCallback +=
               delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                        System.Security.Cryptography.X509Certificates.X509Chain chain,
                        System.Net.Security.SslPolicyErrors sslPolicyErrors)
               {
                   return true; // **** Always accept, NOT VIABLE FOR PRODUCTION.
               };
            
        }

  private static Authenticate Authenticate()
        {
            setTLS();

            string url = Config.URL + "token";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.KeepAlive = false;
            request.Headers.Add("Authorization", "Basic " + Utility.Base64Encode(string.Format("{0}:{1}", Config.ConsumerKey, Config.SecretKey)));
            
            request.Method = "POST";

            //what I'm sending to the web request on a post.
            string postData = "grant_type=client_credentials&scope=AVS-Status AVS-Ownership AVS-Status-and-Ownership FX-Ratesheets FX-Dealing-Quotes FX-Quotes FX-Deals ACH-Payments-Status ACH-Payments ACH-FBS-File-Status ACH-FBS-Batch-Status Wires-Payments-Template Wires-Payments Wires-Payments-Status TM-Transaction-Search TM-Transaction-Report TM-Balance-Reports";
            
            Byte[] data = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = data.Length;
                        
            // default settings.
            request.Accept = "application/json";        
            request.UserAgent = "Mozilla/5.0";
            request.ContentType = "application/x-www-form-urlencoded";

            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;


            AttachClientCert(ref request);
            

            try
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            catch (WebException ex)
            {
                Result = "FAILURE";
                throw (ex);
            }
            WebResponse response = (HttpWebResponse)request.GetResponse();

            string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            Authenticate auth = JsonConvert.DeserializeObject<ResponseAuthenticate>(responseString).FromAuthenticateResponse();
            
            return auth;

        }

 private static void AttachClientCert(ref HttpWebRequest request)
        {
          
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(Config.Certificate), Config.CertificatePassword, X509KeyStorageFlags.PersistKeySet);
            request.ClientCertificates.Add(cert);
         
        }


 class ResponseAuthenticate
    {
        [JsonProperty("access_token")]
        public string accessToken;

        public string scope;

        [JsonProperty("token_type")]
        public string tokenType;

        [JsonProperty("expires_in")]
        public string expires;

    }

    class Authenticate
    {
        public  string accessToken;
        public  List<string> scope = new List<string>();
        public  string tokenType;
        public  DateTime Expires;
    }

    static class AuthenticateConversion
    {
        public static Authenticate FromAuthenticateResponse(this ResponseAuthenticate r)
        {
            Authenticate a = new Authenticate();
            a.accessToken = r.accessToken;
            foreach (string s in r.scope.Split(new char[] { ' ' }))
                a.scope.Add(s);

            a.tokenType = r.tokenType;

            a.Expires = DateTime.Now.AddSeconds(float.Parse(r.expires));
            return a;
        }
    }

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.