Skip to content
Andrey Katamanov edited this page Dec 8, 2016 · 4 revisions

###Web Api

Metrics.NET allows request metrics on ASP.NET WebApi applications sitting on top of OWIN. Metrics can be configured for WebApi application using the same configuration as described in the OWIN Adapter documentation.

Configuring WebApi requires an additional step to display a request's route template rather than the raw request path as OWIN does not configure routes. The current request's route template needs to be added to the OWIN environment with key "metrics-net.routetemplate". The snippet below shows one example to accomplish this when using attribute routing. A working example can be found in the Owin.Sample project.

    public class SetOwinRouteTemplateMessageHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
CancellationToken cancellationToken)
        {
            var owinContext = request.GetOwinContext();
            if (owinContext == null) return base.SendAsync(request, cancellationToken);
            var routes = request.GetConfiguration().Routes;
            if (routes == null) return base.SendAsync(request, cancellationToken);
            var routeData = routes.GetRouteData(request);
            if (routeData == null) return base.SendAsync(request, cancellationToken);
            var subRoutes = routeData.Values["MS_SubRoutes"] as IHttpRouteData[];
            if (subRoutes == null) return base.SendAsync(request, cancellationToken);
            var routeTemplate = subRoutes[0].Route.RouteTemplate;
            owinContext.Environment.Add("metrics-net.routetemplate", routeTemplate);
            return base.SendAsync(request, cancellationToken);
        }
    }
   
    // Add the message handler to the HttpConfiguration
    httpconfig.MessageHandlers.Add(new SetOwinRouteTemplateMessageHandler());