Wednesday, 6 January 2016

Call Web Api from Mvc Controller



This tutorial will explain how to call a web api from Mvc Controller
Oftenly we will cal web api from Jquery using ajax call but here we call web api from C# using HttpClient library.we call web api’s from Windows application and console application using http client libraries.

So Httpclient libraries are very useful for calling web api from mvc application ,windows application and console application and also windows 8 application.
To enhance the  responsiveness of application we will use Asynchronous programming for that we will use async , await ,Task and  ReadAsync and GetAsync keywords.

Async and Await many methods could not return output immediately, they wait for other asynchronous programs execution. An Async method returns only Void or Task.

Task returns no value if it is void .If a Task<string> returns string value, this is generic type.

The GetAsync method is asynchronous method and it sends http get request , the await keyword is suspends execution until asynchronous method completes, it returns HttpResponseMessage that contains Http response.

If the IsSuccessStatusCode is true the response code contain Json ,the ReadAsync method is deserialize Json object to Users Model and IsSuccessStatusCode property is false it returns error code.

Create a MVC project , add one controller and  Action method to the MVC project and add one view to the corresponding action method ,write the following method.

For fake api  I took this url: http://jsonplaceholder.typicode.com/posts/1

Decorate your attribute with HttpGet Attribute

[HttpGet]
        public async Task<JsonResult> getdata()
        {
            Users user=null;
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                // New code:
                HttpResponseMessage response = await client.GetAsync("posts/1");
                if (response.IsSuccessStatusCode)
                {
                     user = await response.Content.ReadAsAsync<Users>();  
                }
            }

            return Json(user, JsonRequestBehavior.AllowGet);
           
        }
Here Users is Model Class to persist data
public class Users
    {
        public int userId { get; set; }
        public int id { get; set; }
        public string title { get; set; }
        public string body { get; set; }
    }


 In fiddler we will get the following result



  Tags: call api from c#,call web api from C# controller, call web api from Mvc,calling api from C#,
calling api from asp.net,calling api from jquery,call web api  from controller,consume api in C#,consume web api from C#










No comments:

Post a Comment