.NET 5中CreatedAtAction如何引用其他控制器的端点Action?
解决方案
你出现报错的核心原因是:CreatedAtAction默认只会在当前控制器(也就是你代码里的TodoCommandsController)中查找匹配的Action,你要跨控制器引用端点,必须使用带controllerName参数的重载,显式指定目标控制器的名称。
正确写法
return CreatedAtAction( // 目标Action的名称 nameof(TodoQueriesController.GetTodoFromAuthenticatedUserByTitle), // 目标控制器名称,注意要去掉末尾的Controller后缀 "TodoQueries", // 路由参数,和目标Action的入参完全匹配 new { title }, // 返回的响应体内容 new Todo(title, authenticatedUsername));
额外优化方案
你也可以给目标查询接口指定固定的路由名称,使用CreatedAtRoute来生成响应,这种方式不需要关心控制器和Action的命名,更不容易出错:
- 先给查询接口的
HttpGet特性加Name参数:
[HttpGet("my-todo-by-title/{title}", Name = nameof(GetTodoFromAuthenticatedUserByTitle))] [ActionName(nameof(GetTodoFromAuthenticatedUserByTitle))] public ActionResult<Todo> GetTodoFromAuthenticatedUserByTitle([FromRoute] string title)
- 再在创建接口中直接使用路由名调用:
return CreatedAtRoute( nameof(TodoQueriesController.GetTodoFromAuthenticatedUserByTitle), new { title }, new Todo(title, authenticatedUsername));
踩坑说明
- 控制器名传递时必须去掉
Controller后缀,传TodoQueries而非TodoQueriesController - 路由参数的字段名、类型必须和目标Action的入参完全一致,否则也会报路由匹配失败的错误
内容的提问来源于stack exchange,提问作者Question3r
相关产品推荐
相关产品推荐

