C#C
C#4y ago
Sebastian

❔ ASP.NET Core Middleware running only once

Hello!

I have a custom middleware that runs only once and isn't running on every request.
When I put breakpoint into my pipeline or into my custom middleware it won't break or run.
Any ideas why?
var builder = WebApplication.CreateBuilder(args);

// Other stuff

builder.Services.AddCurUserCookie();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
    app.UseExceptionHandler("/Error");

app.UseRequestLogger();

app.UseStaticFiles();

app.UseCors();
app.UseAuthentication();
app.UseAuthorization();

// My custom middleware
app.UseCurUserCookie();

app.MapControllers();

app.Run();


public interface ICurUserCookie
{
    int CurUserId { get; set; }
}

public class CurUserCookie : ICurUserCookie
{
    public int CurUserId { get; set; }
}

public static class CurUserCookieEx
{
    public static void AddCurUserCookie(this IServiceCollection services)
    {
        services.AddScoped<ICurUserCookie, CurUserCookie>();
    }

    public static void UseCurUserCookie(this IApplicationBuilder app)
    {
        app.Use(async (ctx, next) =>
        {
            // Do stuff here

            await next();
        });
    }
}
Was this page helpful?