从MVC控制器调用Web API [英] Calling Web API from MVC controller

查看:464
本文介绍了从MVC控制器调用Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MVC5项目解决方案中有一个WebAPI控制器. WebAPI有一种方法可将特定文件夹中的所有文件作为Json列表返回:

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:\\"}, {...}]

我想从HomeController调用此方法,将Json响应转换为List<QDocument>,然后将此列表返回到Razor视图.此列表可能为空:[]如果文件夹中没有文件.

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.

这是APIController:

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")
         };
    }               
}

这是我的HomeController:

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;}
   .....
}

那我怎么打这个电话?

推荐答案

从我的HomeController中,我想调用此Method并将Json响应转换为List

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

不,你不知道.您真的不想在代码触手可及的时候增加HTTP调用和(反)序列化的开销.甚至在同一集合中!

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!

您的ApiController仍然违反(我的首选)惯例.让它返回一个具体类型:

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

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

如果您不想这样做,并且绝对确定需要返回HttpResponseMessage,那么仍然绝对没有

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;
    }
}

无论哪种方式,您都可以直接从MVC控制器调用此类或ApiController:

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);
    }
}

但是,如果您确实必须执行HTTP请求,则可以使用HttpWebRequestWebClientHttpClientRestSharp,所有这些教程都已经存在.

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.

这篇关于从MVC控制器调用Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆