ASP.NET C# WebApp passing named parameters to custom middleware using app.UseMiddleware

110 Views Asked by At

C# aspnet webapp, I have the following constructor in my middleware:

    public MiddlewareCustomRuntimeExceptionHandler (RequestDelegate next, ILogger<MiddlewareCustomRuntimeExceptionHandler> logger, bool showDeveloperDebugInfo, bool sessionEnabled) {
        _next = next;
        _logger = logger;
        _showDeveloperDebugInfo = showDeveloperDebugInfo;
        _sessionEnabled = sessionEnabled;
    }

This works fine and as expected, true and false values are passed correctly to parameters showDeveloperDebugInfo and sessionEnabled:

    app.UseMiddleware<MiddlewareCustomRuntimeExceptionHandler>(true, false);

But I would rather pass the parameters showDeveloperDebugInfo and sessionEnabled as named parameters.

This does not work:

    app.UseMiddleware<MiddlewareCustomRuntimeExceptionHandler>(
        showDeveloperDebugInfo: true,
        sessionEnabled: true
    );

This one reports The best overload for 'UseMiddleware' does not have a parameter named 'next' :

    app.UseMiddleware<MiddlewareCustomRuntimeExceptionHandler>(
        next: null,
        Logger: null,
        showDeveloperDebugInfo: true,
        sessionEnabled: true
    );

What is the correct syntax or is it impossible to use named parameters here?

I had the following setup:

  • Visual Studio Code: 1.83.1

  • .NET SDKs installed: 7.0.403

  • .NET runtimes installed: Microsoft.AspNetCore.App 7.0.13, Microsoft.NETCore.App 7.0.13, Microsoft.WindowsDesktop.App 7.0.13

  • Windows 11, Version: 10.0.22621

1

There are 1 best solutions below

1
On BEST ANSWER

Middleware does not support passing parameters directly.

If you want pass the params, you can try this.

enter image description here

MyMiddleware.cs

using Microsoft.Extensions.Options;

namespace coremvc
{
    public class MyMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<MyMiddleware> _logger;
        private readonly MiddleOptions _options;

        public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger, IOptions<MiddleOptions> options)
        {
            _next = next ?? throw new ArgumentNullException(nameof(next));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _options = options?.Value ?? throw new ArgumentNullException(nameof(options));
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                if (_options.ShowDeveloperDebugInfo)
                {
                    Console.WriteLine("Developer debug info is enabled.");
                }

                if (_options.SessionEnabled)
                {
                    Console.WriteLine("Session is enabled.");
                }

                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An exception occurred.");
                if (_options.ShowDeveloperDebugInfo)
                {
                    Console.WriteLine("An exception occurred: " + ex.Message);
                }

                throw; // or handle the exception
            }
        }
    }
    public class MiddleOptions
    {
        public bool ShowDeveloperDebugInfo { get; set; }
        public bool SessionEnabled { get; set; }
    }
}

Program.cs

namespace coremvc
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            builder.Services.Configure<MiddleOptions>(options =>
            {
                options.ShowDeveloperDebugInfo = true; // Or get from IConfiguration
                options.SessionEnabled = false; // Or get from IConfiguration
            });


            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseMiddleware<MyMiddleware>();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}