Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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 ?

like image 598
Christopher J. Avatar asked Dec 03 '22 15:12

Christopher J.


1 Answers

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");
}
like image 152
Mike Avatar answered Dec 09 '22 14:12

Mike