gpt4 book ai didi

c# - 从 MVC Controller 调用 Web API

转载 作者:IT王子 更新时间:2023-10-29 04:33:34 25 4
gpt4 key购买 nike

我的 MVC5 项目解决方案中有一个 WebAPI Controller 。WebAPI 有一个方法可以将特定文件夹中的所有文件作为 Json 列表返回:

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

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

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

这是我的家庭 Controller :

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

最后这是模型,以备不时之需:

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

那么我该如何调用呢?

最佳答案

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

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

您的 ApiController 违反了 (my preferred) convention反正。让它返回具体类型:

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

如果你不想要那个并且你绝对确定你需要返回HttpResponseMessage,那么仍然绝对没有need to bother with calling JsonConvert.SerializeObject() yourself :

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

再一次,您不希望 Controller 中有业务逻辑,因此您将其提取到一个为您完成工作的类中:

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

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

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

return View(listOfFiles);
}
}

但是如果你真的、真的必须做一个 HTTP 请求,你可以使用 HttpWebRequestWebClientHttpClientRestSharp,对于所有这些都有大量的教程。

关于c# - 从 MVC Controller 调用 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29699884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com