Skip to content

Instantly share code, notes, and snippets.

@akunzai
Last active May 17, 2022 13:48
Show Gist options
  • Save akunzai/65082b2896b2b92ca80638bb44f110bc to your computer and use it in GitHub Desktop.
Save akunzai/65082b2896b2b92ca80638bb44f110bc to your computer and use it in GitHub Desktop.
Analysis ASP.NET Core middleware pipeline
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Http;
public class MiddlewareDiagnosticObserver : IObserver<KeyValuePair<string,object?>>
{
public void OnCompleted()
{
// Do nothing
}
public void OnError(Exception error)
{
// Do nothing
}
public void OnNext(KeyValuePair<string, object?> value)
{
// https://github.com/dotnet/aspnetcore/blob/v6.0.0/src/Middleware/MiddlewareAnalysis/src/AnalysisMiddleware.cs
if (value.Key == "Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareStarting" && value.Value != null)
{
var name = GetPropertyValue<string>(value.Value,"name");
var httpContext =GetPropertyValue<HttpContext>(value.Value,"httpContext");
Console.WriteLine($"MiddlewareStarting: {name}; {httpContext.Request.Path}");
}
if (value.Key == "Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareFinished" && value.Value != null)
{
var name = GetPropertyValue<string>(value.Value,"name");
var httpContext =GetPropertyValue<HttpContext>(value.Value,"httpContext");
Console.WriteLine($"MiddlewareFinished: {name}; {httpContext.Response.StatusCode}");
}
if (value.Key == "Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareException" && value.Value != null)
{
var name = GetPropertyValue<string>(value.Value,"name");
var exception =GetPropertyValue<Exception>(value.Value,"exception");
Console.WriteLine($"MiddlewareException: {name}; {exception.Message}");
}
}
private static T GetPropertyValue<T>(object obj, string propertyName)
{
return (T)obj.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public)?.GetValue(obj)!;
}
}
var builder = WebApplication.CreateBuilder(args);
// dotnet add package Microsoft.AspNetCore.MiddlewareAnalysis
builder.Services.AddMiddlewareAnalysis();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
var diagnosticListener = app.Services.GetRequiredService<DiagnosticListener>();
diagnosticListener.Subscribe(new MiddlewareDiagnosticObserver());
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment