When I ran into this I felt like it would be more useful to have the actual text of the route as the operation name, rather than try to identify all the different ways an ID could be constructed.
The problem is that route template exists down the tree from HttpRequestMessage
, but in a TelemetryInitializer
you end up with only access to HttpContext.Current.Request
which is an HttpRequest
.
They don't make it easy but this code works:
public class AiRewriteUrlsFilter : System.Web.Http.Filters.ActionFilterAttribute
{
internal const string AiTelemetryName = "AiTelemetryName";
public override void OnActionExecuting(HttpActionContext actionContext)
{
string method = actionContext.Request?.Method?.Method;
string routeData = actionContext.ControllerContext?.RouteData?.Route?.RouteTemplate;
if (!string.IsNullOrEmpty(routeData) && routeData.StartsWith("api/1.0/") && HttpContext.Current != null)
{
HttpContext.Current.Items.Add(AiTelemetryName, $"{method} /{routeData}");
}
base.OnActionExecuting(actionContext);
}
}
public class AiRewriteUrlsInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
if (telemetry is RequestTelemetry rTelemetry && HttpContext.Current != null)
{
string telemetryName = HttpContext.Current.Items[AiRewriteUrlsFilter.AiTelemetryName] as string;
if (!string.IsNullOrEmpty(telemetryName))
{
rTelemetry.Name = telemetryName;
}
}
}
}