Navigation

Thursday 10 November 2016

Calling a Web API Through C# (Console Application)

STEP:1  In Visual Studio 2012, create a new console application 


STEP:2  Install the Web API Client Libraries


Use NuGet Package Manager to install the Web API Client Libraries package.

Tools=> NuGet Package Manager=>Manage NuGet Package Manager Solution..

Search and install following package.


Microsoft. Asp Net. WebApi. Client

STEP:3   Paste the following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace WebApiData
{
    public class Posts
        {
            public int userId { get; set; }
            public int id { get; set; }
            public string title { get; set; }
            public string body { get; set; }
        }
   public class Program
    {
        static string apiPath = "https://jsonplaceholder.typicode.com/posts/";
        static HttpClient client = new HttpClient();
        static void Main(string[] args)
        {
            RunAsync().Wait();
        }
        static void ShowProduct(List<Posts> Posts)
        {
            foreach (Posts prod in Posts)
            {
                Console.WriteLine("userId :" + prod.userId + " title :" + prod.title);
            }
         
        }

        // Calling Through GetAsync() Method
        static async Task<List<Posts>> GetProductAsync(string path)
        {
            List<Posts> Posts = null;
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.IsSuccessStatusCode)
            {
                Posts = await response.Content.ReadAsAsync<List<Posts>>();
            }
            return Posts;
        }
        static async Task RunAsync()
        {
            client.BaseAddress = new Uri(apiPath);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new     MediaTypeWithQualityHeaderValue("application/json"));
            try
            {   // Get the Posts
                List<Posts> posts = await GetProductAsync(client.BaseAddress.AbsoluteUri);
                ShowProduct(posts);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }

    }
}
-----------------------End of Code------------------------------------------------

//Calling WebApi through PostAsync() Method

public static void fnPostInsDataAsync()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:49602/");
            client.DefaultRequestHeaders.Accept.Clear();
            var formVars = new Dictionary<string, string>();
            formVars.Add("Param", "Some Value");
            formVars.Add("Param1", "Some Value");
            var content = new FormUrlEncodedContent(formVars);
            var response = client.PostAsync("api/palacesports/fntext",content).Result;
            if (response.IsSuccessStatusCode)
            {
                // your code on success
            }
        }



   //Example function in WebApi 

For 'FormDataCollection'  object use following Name Space

 using System.Net.Http.Formatting;


       [HttpPost]
        public string fntest(FormDataCollection obj)
        {

            string ParamValue = obj.Get("param");
            string ParamValue1 = obj.Get("param1");
            return "";
        }


         

     // If the above WebApi function creates a problem you can use this way. But no change on 'fnPostInsDataAsync()'
        

       public class Param
        {
            public string Param get; set; }
            public string Param1get; set; }

        }

        [HttpPost]
        public string fntest(Param obj)
        {
            string ParamValue= obj.Param;
            string ParamValue1= obj.Param1;
            string Return = "";
        }

       

No comments:

Post a Comment