Search This Blog

Tuesday 27 November 2018

Call one web api from another web api in c#


Step 1: - Create WebApi 1 project

Step 2: - Copy Past following code in Controller Action

using System.Net.Http;

[HttpGet]
public HttpResponseMessage Test1(string value)
{
    return Request.CreateResponse(HttpStatusCode.OK, "You pass the value is : " + value);
}

[HttpPost]
public Author Test2(Author value)
{
    value.Status = "OK";

    return value;
}

Step 3: - Create Author Class in Models folder

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string Status { get; set; }
}

Step 4: - Open WebApiConfig.cs and Add {action} in routeTemplate

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional });
}

Step 5: - Create WebApi 2 project

Step 6: - Copy Past following code in Controller Action


using System.Net.Http;

[HttpGet]
public string Test1(string value)
{
    string responseString = string.Empty;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:65346/");//WebApi 1 project URL
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var response = client.GetAsync("api/default/Test1/?value=" + value + "").Result;
        if (response.IsSuccessStatusCode)
        {
            responseString = response.Content.ReadAsStringAsync().Result;
        }
    }
    return responseString;
}

[HttpPost]
public Author Test2(Author value)
{
    string responseString = string.Empty;
    Author objAuthor = new Author();
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:65346/");//WebApi 1 project URL
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        StringContent content = new StringContent(JsonConvert.SerializeObject(value), Encoding.UTF8, "application/json");
        var response = client.PostAsync("api/default/Test2", content).Result;
        if (response.IsSuccessStatusCode)
        {
            responseString = response.Content.ReadAsStringAsync().Result;
            objAuthor = response.Content.ReadAsAsync<Author>().Result;
        }
    }
    return objAuthor;
}

Step 7: - Create Author Class in Models folder

public class Author
{
    public int Id { getset; }
    public string FirstName { getset; }
    public string LastName { getset; }
    public string Address { getset; }
    public string Status { getset; }
}


Step 8: - Open WebApiConfig.cs and Add {action} in routeTemplate

public static void Register(HttpConfiguration config)

{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional });
}

Step 9: - Run both the project one by one

Step 10: - Use Postman to test WebApi 2 project

Note: - Copy URL of WebApi 1 project and change BaseAddress of WebApi 2 project

Step 11: - (GET Request) Copy Past URL (http://localhost:49317/api/default/test1?value=123) in Postman and Click Send button

Step 12: - (POST Request) Copy Past URL (http://localhost:49317/api/default/test2) in Postman and Copy Past following Json to Request body and Click Send button

Json
{
"Id":1,
"FirstName":"Ram",
"LastName":"G",
"Address":"Malad"
}