gpt4 book ai didi

c# - 结果过滤器在 ASP.NET Core 中如何工作?

转载 作者:行者123 更新时间:2023-12-05 02:47:55 30 4
gpt4 key购买 nike

谁能解释一下 ASP.NET Core MVC 中 Action Filter 和 Result Filter 的区别?我真的没有阅读文档。我们在此处的图表中看到的执行结果到底是什么(最底部的灰色框):enter image description here

文档中说

Action filters can change the result returned from the action.

如果它已经改变了结果,为什么我们需要一个结果过滤器?

最佳答案

根据微软文档:

Action filters:

  • Run code immediately before and after an action method is called.
  • Can change the arguments passed into an action.
  • Can change the result returned from the action.
  • Are not supported in Razor Pages.

但是,ResultFilter在执行上有一点不同:

Result filters run code immediately before and after the execution of action results. They run only when the action method has executed successfully. They are useful for logic that must surround view or formatter execution.

假设您想为具有大量属性的 User 模型向客户端返回一个 API 响应。您可以简单地创建基于 API 模型契约(Contract)的响应,如下所示:

public class UserDetailFilter : ResultFilterAttribute
{
public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
var result = context.Result as ObjectResult;
if (result?.Value is UserResponse value)
result.Value = new
{
Id = value.Id,
Username = value.Username,
Fullname = value.Fullname,
Mobile = value.Mobile,
Email = value.Email,
UpdatedAt = value.UpdatedAt
};
await next();
}
}

关于c# - 结果过滤器在 ASP.NET Core 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64723787/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com