使用 Application Insights 抑制 "The controller for path '/' was not found or does not implement IController." 服务器端

Suppress "The controller for path '/' was not found or does not implement IController." Server-Side with Application Insights

我知道这个讨论(源端解决没有例外):https://social.msdn.microsoft.com/Forums/vstudio/en-US/cb944fc4-4410-4e49-ba0b-43e675fe2173/ignoring-certain-exeptions-not-implementing-icontroller-bad-url?forum=ApplicationInsights

我有同样的问题,因为我不想用机器人产生的流量污染我的异常日志(我们只有 Web API 控制器)。我能够使用遥测处理器忽略那些服务器请求(通常显示在 "Failed Requests" 中)并简单地 return 在 404 上。

但是,无法摆脱异常条目 - 有没有人知道一个设置/过滤器/你的名字,它可以让我决定服务器端(在它们被发送之前)哪个异常是否传送到 Application Insights?

您需要按照此处所述实施自定义 ITelemetryProcessorhttps://docs.microsoft.com/en-gb/azure/azure-monitor/app/api-filtering-sampling#filtering

public class ControllerNotImplementedTelemetryProcessor : ITelemetryProcessor
{
    private ITelemetryProcessor Next { get; }

    public void Process(ITelemetry item)
    {
        var exception = item as ExceptionTelemetry;

        if (exception != null && exception.Exception.GetType() == typeof(HttpException) && exception.Exception.Message.Contains("was not found or does not implement IController"))
            return;

        Next.Process(item);
    }

    public ControllerNotImplementedTelemetryProcessor(ITelemetryProcessor next)
    {
        Next = next;
    }
}

注册自定义处理器发生在 Global.ascx:

TelemetryConfiguration.Active.TelemetryProcessorChainBuilder
    .Use(next => new ControllerNotImplementedTelemetryProcessor(next))
    .Build();

请注意,这显然是一个非常粗略的过滤器,根据错误消息的语言,英语可能是可以接受的,但也可能导致误报。