代码之家  ›  专栏  ›  技术社区  ›  mickl

web api+azure应用洞察将数据从actionfilter传递到itelemetryprocessor

  •  2
  • mickl  · 技术社区  · 6 年前

    我想自定义我的应用程序洞察日志记录行为。所以我想在我的 动作过滤器 然后把旗子读进去 ITelemetryprocessor公司 是的。

    public class MyCustomFilterAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            //perform some logic and set the flag here
        }
    }
    

    然后

    public class TelemetryFilter : ITelemetryProcessor
    {
        public void Process(ITelemetry item)
        {
            var request = item as RequestTelemetry;
            //read the flag here and terminate processing
        }
    }
    

    有可能吗?这两种类型之间有共享的tempdata吗?我想避免像设置临时标题之类的黑客攻击。提前谢谢。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Jayendran    6 年前

    我不确定这是否有用。但我希望会。

    使用 Activity.Current

        public void Initialize(ITelemetry telemetry)
        {
            Activity current = Activity.Current;
    
            if (current == null)
            {
                current = (Activity)HttpContext.Current?.Items["__AspnetActivity__"];
    //put your code here
            }
    }
    

    参考这个 SO

        2
  •  1
  •   cijothomas    6 年前

    在可以访问httpcontext的地方编写一个遥测初始化器。

    //遥测初始化器

    public void Initialize(ITelemetry telemetry)
        {
         var ctx = HttpContext.Current; // Telemetry Initialzer runs in same thread as the request.
         var request = item as RequestTelemetry;
         req.Properties.Add("MyActionFilter", "MyActionFilterValue")
         ...
        }
    

    //遥测处理器

    public void Process(ITelemetry item)
        {
            var request = item as RequestTelemetry;
            //read the flag here and terminate processing
            if(req.Properties["MyActionFilter"] == "somthing")
            {
            ...
            }
        }
    

    https://docs.microsoft.com/en-us/azure/application-insights/app-insights-api-filtering-sampling#itelemetryprocessor-and-itelemetryinitializer

    对于ASP.NET核心,注入 IHttpContextAccessor 到遥测初始化器构造函数可以获取上下文,如下所示: https://github.com/Microsoft/ApplicationInsights-aspnetcore/blob/develop/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/TelemetryInitializerBase.cs