Return a view with ASP.NET Core API

坚强是说给别人听的谎言 提交于 2019-12-10 20:23:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!