Update to the last post - set the name in MVC Web API

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.

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

comments powered by Disqus