how to set the output type List<string> in a middleware in .NET Core 2.1?

80 Views Asked by At

I have this middleware class when I want to show a List<string> in the output:

namespace WebAspNetCore2_1
{
    public class LearningMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<LearningMiddleware> _logger_log;
        private readonly List<string> logger;

        public LearningMiddleware(RequestDelegate next,ILogger<LearningMiddleware> logger_log)
        {
            _next = next;
            _logger_log = logger_log;

            List<string> _logger = new List<string>
                                       {
                                           ("EUR/USD"),
                                           ("1.0500")
                                       };

            logger = _logger;
        }

        public Task Invoke(HttpContext httpContext)
        {
            _logger_log.Log(Microsoft.Extensions .Logging.LogLevel.Information,"information of logger",logger[0]);
            return _next(httpContext);
        }
    }
}

I have debugged my code but seen to be correct, my List<> is filled, I don't know why the compiler is throwing this exception:

InvalidOperationException: Could not create an instance of type Microsoft.Extensions.Logging.ILogger`1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'logger' parameter a non-null default value.

i thought was the order declaration in StartUp, but not

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       // app.UseLearningMiddleware();            
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

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

        app.UseMiddleware<LearningMiddleware>();
        app.UseMvc();
    }

link in video for detail evidence: https://youtu.be/2FoLvhLweYo

1

There are 1 best solutions below

5
Tiny Wang On

I tested your code in my side but it worked well... I created a new asp.net core 2.1 MVC project and create a middleware. In StartUp.cs, I put app.UseMiddleware<MyMiddleware>(); just before app.UseMvc(routes =>

enter image description here

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace WebApplication2
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class MyMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<MyMiddleware> _logger_log;
        private readonly List<string> logger;

        public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger_log)
        {
            _next = next;
            _logger_log = logger_log;
            List<string> _logger = new List<string>
                                       {
                                           ("EUR/USD"),
                                           ("1.0500")
                                       };
            logger = _logger;
        }

        public Task Invoke(HttpContext httpContext)
        {
            _logger_log.Log(Microsoft.Extensions.Logging.LogLevel.Information, "information of logger", logger[0]);
            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class MyMiddlewareExtensions
    {
        public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyMiddleware>();
        }
    }
}