【问题标题】:Custom Result in Net 6 Minimal APINet 6 Minimal API 中的自定义结果
【发布时间】:2021-11-29 21:30:58
【问题描述】:

在 ASP.NET Core 5 中,我有一个自定义操作结果,如下所示:

public class ErrorResult : ActionResult {

  private readonly IList<Error> _errors;

  public ErrorResult(IList<Error> errors) {
    _errors = errors;
  }

  public override async Task ExecuteResultAsync(ActionContext context) {

    // Code that creates Response

    await result.ExecuteResultAsync(context);

  }

}

然后在控制器操作上我会:

return new ErrorResult(errors);

如何在 NET 6 Minimal API 中做类似的事情?

我一直在研究它,我认为我应该实现 IResult。

但我不确定这是否是解决方案或如何解决。

【问题讨论】:

  • ActionResult 不能工作? ActionResult 可以在 .net 6 中使用。

标签: asp.net-core .net-6.0


【解决方案1】:

如果你还想使用 MVC (Model-View-Controller),你仍然可以使用自定义 ActionResult。

如果您只想使用 Minimal API 进行响应,则必须实现 IResultTask&lt;IResult&gt;ValueTask&lt;IResult&gt;

app.MapGet("/hello", () => Results.Ok(new { Message = "Hello World" }));

以下示例使用内置结果类型来自定义响应:

app.MapGet("/api/todoitems/{id}", async (int id, TodoDb db) =>
         await db.Todos.FindAsync(id) 
         is Todo todo
         ? Results.Ok(todo) 
         : Results.NotFound())
   .Produces<Todo>(200)
   .Produces(404);

您可以在此处找到更多 IResult 实现sampleshttps://github.com/dotnet/aspnetcore/tree/main/src/Http/Http.Results/src

链接:Minimal APIs overview | Microsoft Docs

【讨论】:

    猜你喜欢
    • 2022-06-11
    • 2023-01-09
    • 2022-08-05
    • 1970-01-01
    • 2022-01-13
    • 2022-09-28
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    相关资源
    最近更新 更多