Create ASP.NET Web API And Consume WEB API In Console Application Using HTTP Client With Basic Authentication

.Create ASP .NET Web API to create lead in dynamic CRM And consume WEB API in console application using HTTP Client with Basic Authentication.
 
What is Web API?
 
The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile, etc.
 
Why Web API?
 
To consume third party data using mobile devices, tablets, browsers Web API is very usefull. Web API is easy to consume, less configuration required as compare to consume web services. Web API returns data in JSON as well as XML format.
 
In this blog, we are going to learn how to consume Web API in asp. Net console application using HTTP client with basic authentication.
 
In this blog, we are creating new lead in Dynamic CRM using ASP.Net Web API.
 
First, we will create new Web API then we are going to consume the API.
 
Please follow below steps to create Web API and consume it in Console Application.
 
Create new project in visual studio File – New Projet – ASP .NET Web Application – Select empty template – checked checkbox for Web API - OK.
 
Create new controller rename as LeadController Right click on Controller folder – Add – Controller,
 
Add below assembly references,
  • Microsoft.Xrm.Sdk
  • Microsoft.Xrm.Client
Configure connection string to connect with Dynamic CRM in App.config file
  1. <connectionStrings>  
  2.    <add name="CRMConnectionString" connectionString="Url=https://***.crm8.dynamics.com; Username=***; Password=***; AuthType=Office365;" />  
  3. </connectionStrings>  
For Basic Authentication create new class file as BasicAuthenticationAttribute.cs and add below code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Security.Principal;  
  7. using System.Threading;  
  8. using System.Web;  
  9. using System.Web.Http.Controllers;  
  10. using System.Web.Http.Filters;  
  11. namespace TrialWebAPI {  
  12.     public class BasicAuthenticationAttribute: AuthorizationFilterAttribute {  
  13.         public override void OnAuthorization(HttpActionContext actionContext) {  
  14.             if (actionContext.Request.Headers.Authorization != null) {  
  15.                 var authToken = actionContext.Request.Headers.Authorization.Parameter;  
  16.                 // decoding authToken we get decode value in 'Username:Password' format  
  17.                 var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));  
  18.                 // spliting decodeauthToken using ':'  
  19.                 var arrUserNameandPassword = decodeauthToken.Split(':');  
  20.                 // at 0th postion of array we get username and at 1st we get password  
  21.                 if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1])) {  
  22.                     // setting current principle  
  23.                     Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(arrUserNameandPassword[0]), null);  
  24.                 } else {  
  25.                     actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
  26.                 }  
  27.             } else {  
  28.                 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
  29.             }  
  30.         }  
  31.         public static bool IsAuthorizedUser(string Username, string Password) {  
  32.             // In this method we can handle our database logic here...  
  33.             return Username == "Akash" && Password == "Vidhate";  
  34.         }  
  35.     }  
  36. }  
Create new class file as LeadClass.cs and add below code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace TrialWebAPI.Models {  
  6.     public class LeadClass {  
  7.         public string LeadId {  get;  set;  }  
  8.         public string Subject {  get;  set;  }  
  9.         public string FirstName {  get;  set;  }  
  10.         public string LastName {  get;  set;  }  
  11.         public string Company {  get;  set;  }  
  12.         public string Website {  get;  set;  }  
  13.         public Address Address {  get;  set;  }  
  14.     }  
  15.     public class Address {  
  16.         public string Address_Line1 {  get;  set;  }  
  17.         public string Address_Line2 {  get;  set;  }  
  18.         public string Address_Line3 {  get;  set;  }  
  19.         public string City {  get;  set;  }  
  20.         public string State {  get;  set;  }  
  21.         public string Postal_Code {  get;  set;  }  
  22.         public string Country {  get;  set;  }  
  23.     }  
  24. }  
Add below code in LeadController.cs file,
[BasicAuthentication] with GET and POST method is used for authentication purpose for API security.

  1. using Microsoft.Xrm.Sdk;  
  2. using Microsoft.Xrm.Client;  
  3. using Microsoft.Xrm.Client.Services;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Configuration;  
  7. using System.Linq;  
  8. using System.Net;  
  9. using System.Net.Http;  
  10. using System.Web.Http;  
  11. using TrialWebAPI.Models;  
  12. namespace TrialWebAPI.Controllers {  
  13.     public class LeadController: ApiController {  
  14.         #region GET method
  15.         [BasicAuthentication]  
  16.         public HttpResponseMessage Get() {  
  17.             LeadClass lead = new LeadClass();  
  18.             Address addr = new Address();  
  19.             lead.Address = addr;  
  20.             return Request.CreateResponse(HttpStatusCode.Created, lead);  
  21.         }  
  22.         #endregion  
  23.         # region POST method
                [BasicAuthentication]
      
  24.             [HttpPost]  
  25.         public HttpResponseMessage POST(LeadClass leadClass) {  
  26.             ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;  
  27.             CrmConnection con = CrmConnection.Parse(ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString);  
  28.             OrganizationService service = null;  
  29.             service = new OrganizationService(con);  
  30.             try {  
  31.                 Entity lead = new Entity("lead");  
  32.                 lead["subject"] = leadClass ? .Subject;  
  33.                 lead["firstname"] = leadClass ? .FirstName;  
  34.                 lead["lastname"] = leadClass ? .LastName;  
  35.                 lead["companyname"] = leadClass ? .Company;  
  36.                 lead["websiteurl"] = leadClass ? .Website;  
  37.                 lead["address1_line1"] = leadClass ? .Address ? .Address_Line1;  
  38.                 lead["address1_line2"] = leadClass ? .Address ? .Address_Line2;  
  39.                 lead["address1_line3"] = leadClass ? .Address ? .Address_Line3;  
  40.                 lead["address1_city"] = leadClass ? .Address ? .City;  
  41.                 lead["address1_stateorprovince"] = leadClass ? .Address ? .State;  
  42.                 lead["address1_postalcode"] = leadClass ? .Address ? .Postal_Code;  
  43.                 lead["address1_country"] = leadClass ? .Address ? .Country;  
  44.                 Guid guid = service.Create(lead);  
  45.                 leadClass.LeadId = guid.ToString();  
  46.                 return Request.CreateResponse(HttpStatusCode.Created, leadClass);  
  47.             } catch (Exception ex) {  
  48.                 return Request.CreateErrorResponse(HttpStatusCode.OK, ex.Message);  
  49.             }  
  50.         }#endregion  
  51.     }  
  52. }  
Now to Consume above Web API create new Console Application(refer below steps).
 
Create new cosole application in visual studio File – New Project – Console Application,
 
Create new class file LeadClass.cs,
 
It contains parameters that we have to pass to consume API. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace ConsumeWebAPI {  
  7.     class LeadClass {  
  8.         public string FirstName {  get;  set;  }  
  9.         public string LastName {  get;  set;  }  
  10.         public string Mobile {  get;  set;  }  
  11.         public string EmailID {  get;  set;  }  
  12.     }  
  13. }  
Add below assembly references (using nuget package manager console) in Program.cs file and add below code,
  • System.Net.Http.Formatting.Extension
  • Newtonsoft.Json
In this we have HttpClient for sending/receiving Http request/response, methods of HttpClient are asynchronous, async Task is used for purpose application must be wait till whole task will complete execution.
HttpResponseMessage is used to return message/data from API.

tpResponseMessage is a way of returning a message/data from your action
Program.cs file
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Net.Http;  
  7. using System.Net.Http.Headers;  
  8. using Newtonsoft.Json;  
  9. namespace ConsumeWebAPI {  
  10.     class Program {  
  11.         static void Main(string[] args) {  
  12.             //Call GET method  
  13.             CallGetMethod().Wait();  
  14.             //Call POST method  
  15.             CallPostMethod().Wait();  
  16.         }  
  17.         static async Task CallGetMethod() {  
  18.             using(var client = new HttpClient()) {  
  19.                 client.BaseAddress = new Uri("http://localhost:64990/");  
  20.                 client.DefaultRequestHeaders.Accept.Clear();  
  21.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  22.                 string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes("Akash:Vidhate")); //("Username:Password")  
  23.                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);  
  24.                 #region Consume GET method  
  25.                 HttpResponseMessage response = await client.GetAsync("api/lead/1");  
  26.                 if (response.IsSuccessStatusCode) {  
  27.                     string httpResponseResult = response.Content.ReadAsStringAsync().ContinueWith(task => task.Result).Result;  
  28.                     Console.WriteLine("Result: " + httpResponseResult);  
  29.                 } else {  
  30.                     Console.WriteLine("Internal server Error");  
  31.                 }  
  32.                 Console.ReadKey();  
  33.                 #endregion  
  34.             }  
  35.         }  
  36.         static async Task CallPostMethod() {  
  37.             using(var client = new HttpClient()) {  
  38.                 client.BaseAddress = new Uri("http://localhost:64990/");  
  39.                 client.DefaultRequestHeaders.Accept.Clear();  
  40.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  41.                 string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes("Akash:Vidhate")); //("Username:Password")  
  42.                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);  
  43.                 #region Consume POST Method  
  44.                 var address = new Address() {  
  45.                     Address_Line1 = "",  
  46.                         Address_Line2 = "",  
  47.                         Address_Line3 = "",  
  48.                         City = "",  
  49.                         State = "",  
  50.                         Country = "",  
  51.                         Postal_Code = ""  
  52.                 };  
  53.                 var leadRequest = new LeadClass() {  
  54.                     FirstName = "Akash",  
  55.                         LastName = "Vidhate",  
  56.                         Company = "",  
  57.                         Website = "",  
  58.                         Subject = "",  
  59.                         Address = address  
  60.                 };  
  61.                 HttpResponseMessage responsePost = await client.PostAsJsonAsync("api/lead", leadRequest);  
  62.                 if (responsePost.IsSuccessStatusCode) {  
  63.                     string httpResponseResult = responsePost.Content.ReadAsStringAsync().ContinueWith(task => task.Result).Result;  
  64.                     if (responsePost.ReasonPhrase == "Created") {  
  65.                         LeadClass leadclass = JsonConvert.DeserializeObject < LeadClass > (httpResponseResult);  
  66.                         Console.WriteLine("Lead is created and LeadId is: " + leadclass.LeadId);  
  67.                     } else if (responsePost.ReasonPhrase == "OK") {  
  68.                         Console.WriteLine(httpResponseResult);  
  69.                     }  
  70.                 } else {  
  71.                     Console.WriteLine("Internal server error");  
  72.                 }  
  73.                 Console.ReadKey();  
  74.               #endregion  
  75.             }  
  76.         }  
  77.     }  
  78. }