在.Net Core 中使用ActionFilterAttribute重写OnResultExecuting来实现对返回接口自定义输出:
1、创建 ResultFilter ,继承自 ActionFilterAttribute
public class ResultFilter : ActionFilterAttribute
{
/// <summary>
/// 接口返回前验证
/// </summary>
/// <param name="context"></param>
public override void OnResultExecuting(ResultExecutingContext context)
{
if (context.Result is ObjectResult)
{
var objectResult = context.Result as ObjectResult;
if (objectResult.StatusCode == 203)
{
context.Result = new ObjectResult(new
{
code = objectResult.StatusCode,
msg = new {
ip = $"{context.HttpContext.Connection.RemoteIpAddress}",
info = objectResult.Value,
date = DateTime.Now.ToString("G"), url = requestUrl
},
result = obj
});
}
if (context.Result is ContentResult)
{
context.Result = new ObjectResult(new { code = 200, msg = new { ip = $"{context.HttpContext.Connection.RemoteIpAddress}", info = "OK", date = DateTime.Now.ToString("G"), url = requestUrl }, result = (context.Result as ContentResult).Content });
}
}
}
}
2、添加MVC服务配置过滤器
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc(options =>
{
options.Filters.Add(typeof(ResultFilter));
});
}
自定义响应优雅方式参考 .NET Core AutoWrapper 自定义响应输出
谢谢