c# - 找不到 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。
怎么了?
解决方案
您缺少控制器的路由前缀。您正在使用属性路由,因此您需要包含整个所需的路由。
当前的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
还要注意路由标记的使用,并且已经有提供这些结果的辅助方法,而不是更新响应。
推荐阅读
- c++ - C ++如何确定元素是否存在于动态分配的数组中
- java - SwingWorker 线程同步
- javascript - 为什么我的 React Native 应用程序崩溃了?
- c++ - 来自异步服务器的套接字写入——但不读取
- detox - 在阶段与生产中处理测试的环境变量
- javascript - 如何onClick将文本从a复制到剪贴板
使用 JavaScript/jQuery 标记?
- typescript - 如何在 TypeScript 的 Koa 调试模式下将自定义中间件函数记录到控制台?
- javascript - 来自 XMLHttpRequest 文本的 JS ArrayBuffer
- excel - 库存宏 - 结合步骤和while循环?
- node.js - Firebase 部署在 tsc 命令返回错误