Calling Web API from MVC controller

前端 未结 5 1262
余生分开走
余生分开走 2021-02-01 03:37

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\":\"file

5条回答
  •  一向
    一向 (楼主)
    2021-02-01 04:19

    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 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>(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 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.

提交回复
热议问题