Return 返回服务器生成的标识符以响应最小的变化
Return back server generated identifier in response with minimal changes
我的 objective 是 return 在所有 API 的响应 header 中返回 HttpContext.TraceIdentifier
。
所有API的return类型为IActionResult
。
我看到了创建 middlware
和覆盖 messageHandler
的解决方案。
我只想对 return 进行最小的更改。
目前,我没有干扰默认消息处理程序。
据我所知,您可以尝试使用 asp.net 核心操作过滤器作为全局过滤器或属性来实现您的要求。
您可以在 OnActionExecuted 方法中获取 httpcontext,然后您可以为特定控制器或全局过滤器注册过滤器。
更多详情,您可以参考以下代码:
创建操作过滤器:
public class TestActionFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
var re = context.HttpContext.TraceIdentifier;
context.HttpContext.Response.Headers.Add("TraceIdentifier", re);
}
public void OnActionExecuting(ActionExecutingContext context)
{
//throw new NotImplementedException();
}
}
在网络中将其添加为属性 api 控制器:
[TypeFilter(typeof(TestActionFilter))]
public class WeatherForecastController : ControllerBase
或注册为全局过滤器:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options=>options.Filters.Add(typeof(TestActionFilter)));
}
结果:
我的 objective 是 return 在所有 API 的响应 header 中返回 HttpContext.TraceIdentifier
。
所有API的return类型为IActionResult
。
我看到了创建 middlware
和覆盖 messageHandler
的解决方案。
我只想对 return 进行最小的更改。 目前,我没有干扰默认消息处理程序。
据我所知,您可以尝试使用 asp.net 核心操作过滤器作为全局过滤器或属性来实现您的要求。
您可以在 OnActionExecuted 方法中获取 httpcontext,然后您可以为特定控制器或全局过滤器注册过滤器。
更多详情,您可以参考以下代码:
创建操作过滤器:
public class TestActionFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
var re = context.HttpContext.TraceIdentifier;
context.HttpContext.Response.Headers.Add("TraceIdentifier", re);
}
public void OnActionExecuting(ActionExecutingContext context)
{
//throw new NotImplementedException();
}
}
在网络中将其添加为属性 api 控制器:
[TypeFilter(typeof(TestActionFilter))]
public class WeatherForecastController : ControllerBase
或注册为全局过滤器:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options=>options.Filters.Add(typeof(TestActionFilter)));
}
结果: