【问题标题】:CreatedAction does not accept endpoint action name from another controllerCreatedAction 不接受来自另一个控制器的端点操作名称
【发布时间】:2021-10-20 04:01:38
【问题描述】:

我正在尝试不同的 REST API 设计。我用一个模型和两个控制器创建了一个新的 .Net 5 应用

public sealed record Todo(string Title, string OwnedBy, bool IsDone = false);

public sealed class TodoQueriesController : ControllerBase
{
    [HttpGet("my-todo-by-title/{title}")]
    [ActionName(nameof(GetTodoFromAuthenticatedUserByTitle))]
    public ActionResult<Todo> GetTodoFromAuthenticatedUserByTitle([FromRoute] string title)
    {
        string authenticatedUsername = "foo";
        
        return Ok(new Todo(title, authenticatedUsername));
    }
}

public sealed class TodoCommandsController : ControllerBase
{
    [HttpPost("assign-todo-to-me")]
    public ActionResult<Todo> AssignTodoToAuthenticatedUser([FromBody] string title)
    {
        string authenticatedUsername = "foo";
        
        return CreatedAtAction("???", new { title }, new Todo(title, authenticatedUsername));
    }
}

目前我不知道要传递什么作为CreatedAtAction 的操作名称(以替换"???"

我试过了

  • nameof(TodoQueriesController.GetTodoFromAuthenticatedUserByTitle)
  • "GetTodoFromAuthenticatedUserByTitle"
  • "my-todo-by-title"
  • $"my-todo-by-title/{title}"

但不幸的是,我总是得到 500 分

System.InvalidOperationException:没有路由与提供的值匹配。

如何从另一个控制器引用端点操作?

【问题讨论】:

    标签: c# .net-5


    【解决方案1】:

    您可以将 CreatedAtAction 重载与 controllerName 参数一起使用。

    CreatedAtActionResult CreatedAtAction (string actionName, string controllerName, object routeValues, object value)
    

    查看文档here

    【讨论】:

    • 你的意思是这样吗? CreatedAtAction(nameof(TodoQueriesController.GetTodoFromAuthenticatedUserByTitle), nameof(TodoQueriesController), new { title }, new Todo(title, authenticatedUsername)); 那也没用
    • 我刚刚意识到您正在使用 [FromRoute] 属性。这不适用于 CreatedAtAction,因为无法从路由传递标题。我认为您需要在这种情况下使用 CreatedAtRoute 并将标题值附加到路由字符串,如下所示: CreatedAtRoute(nameof(TodoQueriesController.GetTodoFromAuthenticatedUserByTitle) + title, nameof(TodoQueriesController), new Todo(title, authenticatedUsername));跨度>
    • 抱歉,此方法没有为控制器名称提供重载。我也试过CreatedAtRoute(nameof(TodoQueriesController.GetTodoFromAuthenticatedUserByTitle), new Todo(title, authenticatedUsername));CreatedAtRoute(nameof(TodoQueriesController.GetTodoFromAuthenticatedUserByTitle) + title, new Todo(title, authenticatedUsername));
    • 可以在路由参数中指定控制器。见here
    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    相关资源
    最近更新 更多