Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Web API from MVC controller

I have a WebAPI Controller within my MVC5 project solution. The WebAPI has a method which returns all files in a specific folder as a Json list:

[{"name":"file1.zip", "path":"c:\\"}, {...}]

From my HomeController I want to call this Method, convert the Json response to List<QDocument> and return this list to a Razor view. This list might be empty: [] if there are no files in the folder.

This is the APIController:

public class DocumentsController : ApiController {     #region Methods     /// <summary>     /// Get all files in the repository as Json.     /// </summary>     /// <returns>Json representation of QDocumentRecord.</returns>     public HttpResponseMessage GetAllRecords()     {       // All code to find the files are here and is working perfectly...           return new HttpResponseMessage()          {              Content = new StringContent(JsonConvert.SerializeObject(listOfFiles), Encoding.UTF8, "application/json")          };     }                } 

Here is my HomeController:

public class HomeController : Controller {      public Index()      {       // I want to call APi GetAllFiles and put the result to variable:       var files = JsonConvert.DeserializeObject<List<QDocumentRecord>>(API return Json);       }  } 

Finally this is the model in case you need it:

public class QDocumentRecord {       public string id {get; set;}       public string path {get; set;}    ..... } 

So how can I make this call?

like image 411
A-Sharabiani Avatar asked Apr 17 '15 12:04

A-Sharabiani


People also ask

Can we call Web API from MVC controller?

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.

Can we use Web API in MVC?

First of all, create MVC controller class called StudentController in the Controllers folder as shown below. Right click on the Controllers folder > Add.. > select Controller.. Step 2: We need to access Web API in the Index() action method using HttpClient as shown below.


2 Answers

From my HomeController I want to call this Method and convert Json response to List

No you don't. You really don't want to add the overhead of an HTTP call and (de)serialization when the code is within reach. It's even in the same assembly!

Your ApiController goes against (my preferred) convention anyway. Let it return a concrete type:

public IEnumerable<QDocumentRecord> GetAllRecords() {     listOfFiles = ...     return listOfFiles; } 

If you don't want that and you're absolutely sure you need to return HttpResponseMessage, then still there's absolutely no need to bother with calling JsonConvert.SerializeObject() yourself:

return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles); 

Then again, you don't want business logic in a controller, so you extract that into a class that does the work for you:

public class FileListGetter {     public IEnumerable<QDocumentRecord> GetAllRecords()     {         listOfFiles = ...         return listOfFiles;     } } 

Either way, then you can call this class or the ApiController directly from your MVC controller:

public class HomeController : Controller {     public ActionResult Index()     {         var listOfFiles = new DocumentsController().GetAllRecords();         // OR         var listOfFiles = new FileListGetter().GetAllRecords();          return View(listOfFiles);     } } 

But if you really, really must do an HTTP request, you can use HttpWebRequest, WebClient, HttpClient or RestSharp, for all of which plenty of tutorials exist.

like image 131
CodeCaster Avatar answered Oct 05 '22 17:10

CodeCaster


Its very late here but thought to share below code. If we have our WebApi as a different project altogether in the same solution then we can call the same from MVC controller like below

public class ProductsController : Controller     {         // GET: Products         public async Task<ActionResult> Index()         {             string apiUrl = "http://localhost:58764/api/values";              using (HttpClient client=new HttpClient())             {                 client.BaseAddress = new Uri(apiUrl);                 client.DefaultRequestHeaders.Accept.Clear();                 client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));                  HttpResponseMessage response = await client.GetAsync(apiUrl);                 if (response.IsSuccessStatusCode)                 {                     var data = await response.Content.ReadAsStringAsync();                     var table = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);                  }               }             return View();          }     } 
like image 44
LifeOfPi Avatar answered Oct 05 '22 18:10

LifeOfPi