1- using System ;
1+ using System ;
2+ using System . Net ;
23using System . Threading . Tasks ;
34using Prometheus . Client . Collectors ;
45using Microsoft . AspNetCore . Builder ;
6+ using Microsoft . AspNetCore . Http ;
57
68namespace Prometheus . Client . AspNetCore
79{
@@ -36,8 +38,8 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a
3638 throw new ArgumentException ( $ "MapPath '{ options . MapPath } ' should start with '/'") ;
3739
3840 RegisterCollectors ( options ) ;
39-
40- app . Map ( options . MapPath , coreapp =>
41+
42+ Action < IApplicationBuilder > addMetricsHandler = coreapp =>
4143 {
4244 coreapp . Run ( async context =>
4345 {
@@ -51,18 +53,24 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a
5153
5254 await Task . FromResult ( 0 ) . ConfigureAwait ( false ) ;
5355 } ) ;
54- } ) ;
56+ } ;
57+
58+ if ( options . Port == null )
59+ {
60+ return app . Map ( options . MapPath , addMetricsHandler ) ;
61+ }
5562
56- return app ;
63+ Func < HttpContext , bool > portMatches = context => context . Connection . LocalPort == options . Port ;
64+ return app . Map ( options . MapPath , cfg => cfg . MapWhen ( portMatches , addMetricsHandler ) ) ;
5765 }
5866
5967
6068 private static void RegisterCollectors ( PrometheusOptions options )
6169 {
6270 if ( options . UseDefaultCollectors )
6371 {
64- var metricFactory = options . CollectorRegistryInstance == CollectorRegistry . Instance
65- ? Metrics . DefaultFactory
72+ var metricFactory = options . CollectorRegistryInstance == CollectorRegistry . Instance
73+ ? Metrics . DefaultFactory
6674 : new MetricFactory ( options . CollectorRegistryInstance ) ;
6775
6876 options . Collectors . AddRange ( DefaultCollectors . Get ( metricFactory ) ) ;
0 commit comments