我想从我的 HomeController 调用此方法并将 Json 响应转换为列表
不,你不知道。当代码触手可及时,您确实不想增加 HTTP 调用和(反)序列化的开销。甚至在同一个程序集中!
你的 ApiController 违背了(我的首选)约定 https://stackoverflow.com/questions/20083598/net-web-api-httpresponsemessage-pattern反正。让它返回一个具体类型:
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
如果您不希望这样并且您绝对确定需要返回HttpResponseMessage
,那么仍然绝对没有需要费心打电话JsonConvert.SerializeObject()你自己 https://stackoverflow.com/questions/12563576/web-api-content-in-httpresponsemessage:
return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles);
话又说回来,您不希望控制器中存在业务逻辑,因此您将其提取到一个为您完成工作的类中:
public class FileListGetter
{
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
}
无论哪种方式,您都可以直接从 MVC 控制器调用此类或 ApiController:
public class HomeController : Controller
{
public ActionResult Index()
{
var listOfFiles = new DocumentsController().GetAllRecords();
// OR
var listOfFiles = new FileListGetter().GetAllRecords();
return View(listOfFiles);
}
}
但如果你真的真的必须做一个 HTTP 请求,你可以使用HttpWebRequest
, WebClient
, HttpClient
or RestSharp
,对于所有这些都有大量的教程。