[英]Return a view with ASP.NET Core API
I am writing an ASP.NET Core API and I was wondering how I could return a View in a Controller. 我正在编写一个ASP.NET核心API,我想知道如何在Controller中返回一个View。 The goal is to provide a documentation on this page.
目标是在此页面上提供文档。 What I have tried is to create a Controller class, that returns a ViewResult, like below:
我试过的是创建一个Controller类,它返回一个ViewResult,如下所示:
[Route("api/[controller]")]
public class HomeController : Controller
{
[HttpGet]
public IActionResult Get()
{
return View();
}
}
Then, I have Created a simple view named Index.cshtml in a View/Home repository. 然后,我在View / Home存储库中创建了一个名为Index.cshtml的简单视图。 When I launch the app with /api/home, it does return an Internal Server Error (as logged in the JS console of the browser).
当我使用/ api / home启动应用程序时,它确实返回内部服务器错误(在浏览器的JS控制台中记录)。 Although, if I return a random ObjectResult like so:
虽然,如果我像这样返回一个随机的ObjectResult:
[HttpGet]
public IActionResult Get()
{
return new ObjectResult(new {bonjour = 1});
}
It does return the correct data model. 它确实返回了正确的数据模型。
Does anyone have an idea on how return a View using ASP.NET Core API Tools ? 有没有人知道如何使用ASP.NET Core API Tools返回View?
You need to specify full path to your view, because your action name is Get
not Index
您需要指定视图的完整路径,因为您的操作名称是
Get
not Index
Try this 尝试这个
[HttpGet]
public IActionResult Get()
{
return View("~/Views/Home/Index.cshtml");
}
I think if you define a route on the class you also need to do this for any of the ActionResults so try adding the below: 我想如果你在课程上定义一个路线,你还需要为任何一个ActionResults做这个,所以尝试添加以下内容:
[HttpGet("nameOfThisRoute")]
[Route("nameOfRoute/Get")]
public IActionResult Get()
{
return View();
}
so your Url will be "api/nameOfRoute/Get" 所以你的网址将是“api / nameOfRoute / Get”
More Info: http://www.ryadel.com/en/custom-routing-method-names-in-asp-net-5-mvc-6/ 更多信息: http : //www.ryadel.com/en/custom-routing-method-names-in-asp-net-5-mvc-6/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.