none
Net Core 在Controller套用Middle Ware RRS feed

  • 問題

  • 前輩好,

    我想嘗試在某些Controller或Action下套MiddleWare,但套時一直發生錯誤,錯誤訊息如下:

    InvalidOperationException: Unable to create an instance of type 'KataNetCore.Infrastructure.MiddleWares.FirstMiddleWare'. The type specified in configurationType must not be abstract and must have a parameterless constructor.

    先附上程式碼:

       public void Configure(IApplicationBuilder app,IHostingEnvironment env,IApplicationLifetime applicationLifetime)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    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.UseCookiePolicy();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
    
                //自己寫擴充方法
                app.UseFirstMiddleWare();
    
                //app.Map("/Second", mapApp =>
                // {
                //     mapApp.UseMiddleware<SecondMiddleWare>();
    
                //     mapApp.Run(async context =>
                //     {
                //         await context.Response.WriteAsync("Second. \r\n");
                //     });
                // });
    
                //app.Use(async (context, next) =>
                //{
                //    await context.Response.WriteAsync("Third Middle in. \r\n");
                //    await next.Invoke();
                //    await context.Response.WriteAsync("Third Middle out. \r\n");
                //});
    
                //app.Run(async (context) => { await context.Response.WriteAsync("Hello World! \r\n"); });
    
    
                //applicationLifetime.ApplicationStarted.Register(() => { Program.RecordConsole("ApplicationStarted"); });
                //applicationLifetime.ApplicationStopped.Register(() =>
                //{
                //    Thread.Sleep(5 * 100);
    
                //    Program.RecordConsole("ApplicationStopped");
                //});
                //applicationLifetime.ApplicationStopping.Register(() => { Program.RecordConsole("ApplicationStopping"); });
    
                //app.Run(async (context) => { await context.Response.WriteAsync("Hello World"); });
    
                //var thread = new Thread(new ThreadStart(() =>
                //{
                //    Thread.Sleep(5 * 1000);
    
                //    Program.RecordConsole("Trigger stop WebHost");
                //    applicationLifetime.StopApplication();
                //}));
    
                //thread.Start();
    
                Program.RecordConsole("StartUp.Configure - Called");
            }

       public class HomeController : Controller
        {
            [MiddlewareFilter(typeof(FirstMiddleWare))]
            public IActionResult Index()
            {
                return View();
            }
    }

      public class FirstMiddleWare
        {
            private RequestDelegate _next;
    
            public FirstMiddleWare(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context)
            {
                await context.Response.WriteAsync($"{nameof(FourthMiddleWare)} in. \r\n");
                await _next(context);
                await context.Response.WriteAsync($"{nameof(FourthMiddleWare)} Out. \r\n");
            }
        }

    我如果不在Controller裡面套用FirstMiddleWare,

    而是在Configure中透過Map.Route的方式來套用FirstMiddleWare的話,程式是不會有問題的。

    但還是想知道我這問題是什麼...

    希望前輩能指點一二,謝謝

    2019年9月14日 上午 02:16