使用ASP.NET Core API返回视图 [英] Return a view with ASP.NET Core API

查看:571
本文介绍了使用ASP.NET Core API返回视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个ASP.NET Core API,我想知道如何在Controller中返回一个View.目的是在此页面上提供文档. 我尝试过的是创建一个Controller类,该类返回一个ViewResult,如下所示:

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();
    }
}

然后,我在View/Home存储库中创建了一个名为Index.cshtml的简单视图. 当我使用/api/home启动应用程序时,它会返回内部服务器错误(如浏览器的JS控制台中所记录).虽然,如果我这样返回一个随机的ObjectResult:

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.

有人知道如何使用ASP.NET Core API工具返回视图吗?

Does anyone have an idea on how return a View using ASP.NET Core API Tools ?

推荐答案

您需要指定视图的完整路径,因为您的操作名称是Get而不是Index

You need to specify full path to your view, because your action name is Get not Index

尝试一下

[HttpGet]
public IActionResult Get()
{
    return View("~/Views/Home/Index.cshtml");
}

这篇关于使用ASP.NET Core API返回视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆