我的要求是在将响应发送回客户端之前修改来自控制器的响应。我正在尝试实现IActionResult接口。
public class MyFilter: IActionResult
{
ApiResponse _response = new ApiResponse();
public async Task ExecuteResultAsync(ActionContext context)
{
var httpResponse = context.HttpContext.Response;
if (httpResponse != null)
{
if (httpResponse.StatusCode == 200)
{
if (context.Result.GetType().Equals(typeof(Microsoft.AspNetCore.Mvc.ObjectResult)))
{
_response.Response = ((Microsoft.AspNetCore.Mvc.ObjectResult)context.Result).Value;
_response.Errors = null;
_response.IsSuccess = true;
}
}
}
return ;
}
}我的program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddSingleton<MyFilter>();
builder.Services.AddAppServices();
builder.Services.AddControllers();
builder.Services.AddDataContext(builder.Configuration);
builder.Services.AddRepositories();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();我的控制器具有以下属性
[Route("api/[controller]")]
[ApiController]
[ServiceFilter(typeof(MyFilter))]
public class MyController : ControllerBase
{
}但是,当我调用任何控制器操作方法时,它都不会到达,并给出一个异常作为响应。
有什么东西我完全错过了吗?
https://stackoverflow.com/questions/73163824
复制相似问题