APM tips blog

Blog about application monitoring.

Update to the Last Post - Set the Name in MVC Web API

| Comments

Answering the quesiton in this comment - how to set the name of the request for attribute-based MVC Web API routing. It can be done as an extension to the previous post. Something like this would work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ApplicationInsightsCorrelationHttpActionFilter : System.Web.Http.Filters.ActionFilterAttribute, ITelemetryInitializer
{
    private static AsyncLocal<RequestTelemetry> currentRequestTelemetry = new AsyncLocal<RequestTelemetry>();

    public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        var template = actionContext.RequestContext.RouteData.Route.RouteTemplate;

        var request = System.Web.HttpContext.Current.GetRequestTelemetry();
        request.Name = template;
        request.Context.Operation.Name = request.Name;

        currentRequestTelemetry.Value = request;

        return base.OnActionExecutingAsync(actionContext, cancellationToken);
    }
}

Update: More complete version of this filter is posted by @snboisen at github.

This is an action filter for Web API. In the beggining of action execution the name can be taken from the route data.

Action filter wouldn’t work when execution didn’t reach the controller. So you may need to duplicate the logic in telemetry initializer Initialize method itself. However in this case you’d need to get the currently executing request and it may not always be available.

Comments