【问题标题】:Return a view with ASP.NET Core API使用 ASP.NET Core API 返回视图
【发布时间】:2016-04-30 18:14:35
【问题描述】:

我正在编写一个 ASP.NET Core API,我想知道如何在控制器中返回一个视图。目标是在此页面上提供文档。 我尝试的是创建一个控制器类,它返回一个 ViewResult,如下所示:

[Route("api/[controller]")]
public class HomeController : Controller
{

    [HttpGet]
    public IActionResult Get()
    {
        return View();
    }
}

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

[HttpGet]
    public IActionResult Get()
    {
        return new ObjectResult(new {bonjour = 1});
    }

它确实返回了正确的数据模型。

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

【问题讨论】:

  • 不要在有关 ASP.NET Core 的问题上使用 asp.netasp.net-mvc。它们适用于旧的 ASP.NET 框架

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

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

试试这个

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

【讨论】:

  • @ChristopherJ。欢迎您,请标记为解决方案。
  • 你需要安装一些 nuget 库让它识别 View 类吗?
  • View 是来自 Controller 的方法。您不需要的不仅仅是项目模板中已经嵌入的 ASP.NET Core 包:)
【解决方案2】:

我认为,如果您在类上定义路由,您还需要为任何 ActionResults 执行此操作,因此请尝试添加以下内容:

[HttpGet("nameOfThisRoute")]
[Route("nameOfRoute/Get")]
public IActionResult Get()
{
    return View();
}

所以你的 URL 将是“api/nameOfRoute/Get”

更多信息:http://www.ryadel.com/en/custom-routing-method-names-in-asp-net-5-mvc-6/

【讨论】:

    猜你喜欢
    • 2020-01-13
    • 2014-04-04
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多