【问题标题】:cannot find C# netcore controller找不到 C# 网络核心控制器
【发布时间】:2018-11-17 17:05:42
【问题描述】:

我在现有的 IdentityServer4 项目中添加了一个 netcore 控制器。这是我的代码

namespace IdentityServer4.Quickstart.UI
{
  public class VersionController : Controller
  {
    IVersionService _repository;
    public VersionController(IVersionService repository)
    {
        _repository = repository;
    }
    [HttpGet(nameof(GetBackgroundId))]
    public IActionResult GetBackgroundId()
    {
        return new OkObjectResult(_repository.GetBackgroundId());
    }
    [HttpPut(nameof(SetBackgroundId))]
    public IActionResult SetBackgroundId([FromQuery]int id)
    {
        _repository.SetBackgroundId(id);
        return new NoContentResult();
    }
 }
}

我在 startup.cs 中也有以下代码行

app.UseMvcWithDefaultRoute();

我可以通过以下网址访问账户控制器

http://localhost:5001/account/login

但是,我无法通过以下 url 访问版本控制器:

http://localhost:5001/version/GetBackgroundId

错误码是404。

怎么了?

【问题讨论】:

  • 你能显示路由配置文件的内容吗
  • 没有路由配置文件。我添加了app.UseMvcWithDefaultRoute();

标签: c# asp.net-core identityserver4 asp.net-core-webapi


【解决方案1】:

您缺少控制器的路由前缀。您正在使用属性路由,因此您需要包含整个所需的路由。

当前GetBackgroundId 控制器操作将映射到

http://localhost:5001/GetBackgroundId

向控制器添加路由

[Route("[controller]")]
public class VersionController : Controller {
    IVersionService _repository;
    public VersionController(IVersionService repository) {
        _repository = repository;
    }

    //Match GET version/GetBackgroundId
    [HttpGet("[action]")]
    public IActionResult GetBackgroundId() {
        return Ok(_repository.GetBackgroundId());
    }

    //Match PUT version/SetBackgroundId?id=5
    [HttpPut("[action]")]
    public IActionResult SetBackgroundId([FromQuery]int id) {
        _repository.SetBackgroundId(id);
        return NoContent();
    }
 }

还要注意路由标记的使用,Controller 已经有了提供这些结果的辅助方法,而不是更新响应。

参考Routing to controller actions in ASP.NET Core

【讨论】:

  • 我发帖后发现了这一点。这就是解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 2018-03-13
  • 2019-02-02
  • 1970-01-01
  • 2018-01-10
  • 2020-02-04
相关资源
最近更新 更多