首页 > 解决方案 > 找不到 C# netcore 控制器

问题描述

我在现有的 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。

怎么了?

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

解决方案


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

当前的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还要注意路由标记的使用,并且已经有提供这些结果的辅助方法,而不是更新响应。

参考路由到 ASP.NET Core 中的控制器操作


推荐阅读