.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
- <connectionStrings>
- <add name="CRMConnectionString" connectionString="Url=https://***.crm8.dynamics.com; Username=***; Password=***; AuthType=Office365;" />
- </connectionStrings>
For Basic Authentication create new class file as BasicAuthenticationAttribute.cs and add below code.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Security.Principal;
- using System.Threading;
- using System.Web;
- using System.Web.Http.Controllers;
- using System.Web.Http.Filters;
- namespace TrialWebAPI {
- public class BasicAuthenticationAttribute: AuthorizationFilterAttribute {
- public override void OnAuthorization(HttpActionContext actionContext) {
- if (actionContext.Request.Headers.Authorization != null) {
- var authToken = actionContext.Request.Headers.Authorization.Parameter;
-
- var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
-
- var arrUserNameandPassword = decodeauthToken.Split(':');
-
- if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1])) {
-
- Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(arrUserNameandPassword[0]), null);
- } else {
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
- }
- } else {
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
- }
- }
- public static bool IsAuthorizedUser(string Username, string Password) {
-
- return Username == "Akash" && Password == "Vidhate";
- }
- }
- }
Create new class file as LeadClass.cs and add below code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace TrialWebAPI.Models {
- public class LeadClass {
- public string LeadId { get; set; }
- public string Subject { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Company { get; set; }
- public string Website { get; set; }
- public Address Address { get; set; }
- }
- public class Address {
- public string Address_Line1 { get; set; }
- public string Address_Line2 { get; set; }
- public string Address_Line3 { get; set; }
- public string City { get; set; }
- public string State { get; set; }
- public string Postal_Code { get; set; }
- public string Country { get; set; }
- }
- }
Add below code in LeadController.cs file,
[BasicAuthentication] with GET and POST method is used for authentication purpose for API security.
- using Microsoft.Xrm.Sdk;
- using Microsoft.Xrm.Client;
- using Microsoft.Xrm.Client.Services;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using TrialWebAPI.Models;
- namespace TrialWebAPI.Controllers {
- public class LeadController: ApiController {
- #region GET method
- [BasicAuthentication]
- public HttpResponseMessage Get() {
- LeadClass lead = new LeadClass();
- Address addr = new Address();
- lead.Address = addr;
- return Request.CreateResponse(HttpStatusCode.Created, lead);
- }
- #endregion
- # region POST method
[BasicAuthentication]
- [HttpPost]
- public HttpResponseMessage POST(LeadClass leadClass) {
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
- CrmConnection con = CrmConnection.Parse(ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString);
- OrganizationService service = null;
- service = new OrganizationService(con);
- try {
- Entity lead = new Entity("lead");
- lead["subject"] = leadClass ? .Subject;
- lead["firstname"] = leadClass ? .FirstName;
- lead["lastname"] = leadClass ? .LastName;
- lead["companyname"] = leadClass ? .Company;
- lead["websiteurl"] = leadClass ? .Website;
- lead["address1_line1"] = leadClass ? .Address ? .Address_Line1;
- lead["address1_line2"] = leadClass ? .Address ? .Address_Line2;
- lead["address1_line3"] = leadClass ? .Address ? .Address_Line3;
- lead["address1_city"] = leadClass ? .Address ? .City;
- lead["address1_stateorprovince"] = leadClass ? .Address ? .State;
- lead["address1_postalcode"] = leadClass ? .Address ? .Postal_Code;
- lead["address1_country"] = leadClass ? .Address ? .Country;
- Guid guid = service.Create(lead);
- leadClass.LeadId = guid.ToString();
- return Request.CreateResponse(HttpStatusCode.Created, leadClass);
- } catch (Exception ex) {
- return Request.CreateErrorResponse(HttpStatusCode.OK, ex.Message);
- }
- }#endregion
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsumeWebAPI {
- class LeadClass {
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Mobile { get; set; }
- public string EmailID { get; set; }
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using Newtonsoft.Json;
- namespace ConsumeWebAPI {
- class Program {
- static void Main(string[] args) {
-
- CallGetMethod().Wait();
-
- CallPostMethod().Wait();
- }
- static async Task CallGetMethod() {
- using(var client = new HttpClient()) {
- client.BaseAddress = new Uri("http://localhost:64990/");
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes("Akash:Vidhate"));
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
- #region Consume GET method
- HttpResponseMessage response = await client.GetAsync("api/lead/1");
- if (response.IsSuccessStatusCode) {
- string httpResponseResult = response.Content.ReadAsStringAsync().ContinueWith(task => task.Result).Result;
- Console.WriteLine("Result: " + httpResponseResult);
- } else {
- Console.WriteLine("Internal server Error");
- }
- Console.ReadKey();
- #endregion
- }
- }
- static async Task CallPostMethod() {
- using(var client = new HttpClient()) {
- client.BaseAddress = new Uri("http://localhost:64990/");
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes("Akash:Vidhate"));
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
- #region Consume POST Method
- var address = new Address() {
- Address_Line1 = "",
- Address_Line2 = "",
- Address_Line3 = "",
- City = "",
- State = "",
- Country = "",
- Postal_Code = ""
- };
- var leadRequest = new LeadClass() {
- FirstName = "Akash",
- LastName = "Vidhate",
- Company = "",
- Website = "",
- Subject = "",
- Address = address
- };
- HttpResponseMessage responsePost = await client.PostAsJsonAsync("api/lead", leadRequest);
- if (responsePost.IsSuccessStatusCode) {
- string httpResponseResult = responsePost.Content.ReadAsStringAsync().ContinueWith(task => task.Result).Result;
- if (responsePost.ReasonPhrase == "Created") {
- LeadClass leadclass = JsonConvert.DeserializeObject < LeadClass > (httpResponseResult);
- Console.WriteLine("Lead is created and LeadId is: " + leadclass.LeadId);
- } else if (responsePost.ReasonPhrase == "OK") {
- Console.WriteLine(httpResponseResult);
- }
- } else {
- Console.WriteLine("Internal server error");
- }
- Console.ReadKey();
- #endregion
- }
- }
- }
- }