问题
I am writing an ASP.NET Core API and I was wondering how I could return a View in a Controller. 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:
[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. When I launch the app with /api/home, it does return an Internal Server Error (as logged in the JS console of the browser). Although, if I return a random ObjectResult like so:
[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 ?
回答1:
You need to specify full path to your view, because your action name is Get
not Index
Try this
[HttpGet]
public IActionResult Get()
{
return View("~/Views/Home/Index.cshtml");
}
回答2:
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:
[HttpGet("nameOfThisRoute")]
[Route("nameOfRoute/Get")]
public IActionResult Get()
{
return View();
}
so your Url will be "api/nameOfRoute/Get"
More Info: http://www.ryadel.com/en/custom-routing-method-names-in-asp-net-5-mvc-6/
来源:https://stackoverflow.com/questions/36958467/return-a-view-with-asp-net-core-api