zoukankan      html  css  js  c++  java
  • .netcore返回HellowWorld四种方式(管道配置,管道扩展方法,中间件,IStartupFilter 使用中间件的升级扩展)

    在Startup中,我们看官网可以知道Configuration是注入服务和Configure配置管道,而我们的实现原理是在管道中直接返回HellowWorld,新建一个.netcoreMVC项目

    一,第一种方法,最简单,我们直接在管道实现,在Configure添加一个直接返回的配置,如下代码

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
                ///管道直接返回,不往下执行
                app.Run(async context =>
                {
                    context.Response.ContentType = "text/plain";
                    await context.Response.WriteAsync("Hello World!");
                });
    
    
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }

    二,我们添加一个类,然后写一个管道的扩展方法,如下

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Http.Features;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace TestDoc.MiddleWare
    {
        public static class HellowWorldExtension
        {
            public static IApplicationBuilder UseHellowWorldExtension(this IApplicationBuilder app)
            {
                app.Run(async context =>
                {
                    await context.Response.WriteAsync("HellowWorldExtension");
                });
                return app;
            }
        }
    }

    然后再管道cinfigure配置,如下

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
                ///配置管道的扩展方法
                app.UseHellowWorldExtension();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }

    三,中简件的实现,我们添加中间件 ,如下(PS:1,中间件需要注册服务 2,配置管道)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    
    namespace TestDoc.MiddleWare
    {
        // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
        public class HellowMiddleware
        {
            private readonly RequestDelegate _next;
    
            public HellowTwoMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public Task Invoke(HttpContext httpContext)
            {
    
                return httpContext.Response.WriteAsync("HellowTwoMiddleware");
            }
        }
    
        // Extension method used to add the middleware to the HTTP request pipeline.
        public static class HellowMiddlewareExtensions
        {
            public static IApplicationBuilder UseHellowTwoMiddleware(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware<HellowTwoMiddleware>();
            }
        }
    }

    再Startup如下代码配置

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using TestDoc.Infrastructure.Ex;
    using TestDoc.MiddleWare;
    
    namespace TestDoc
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllersWithViews();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                ///使用中间件
                app.UseHellowMiddleware();
    
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

    四,中间件的扩展,我们看第三点知道,注入中间件要配置ConfigureServices和Configure两步,现在我们用IStartupFilter升级扩展下,先添加一个类,如下

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Http.Features;
    using Microsoft.Extensions.DependencyInjection;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace TestDoc.MiddleWare
    {
        public static class HellowWorldMiddleWareExtension
        {
            public static IServiceCollection AddHellowWorldMiddleWareExtension(this IServiceCollection services)
            {
                services.AddTransient<IStartupFilter, HellowWorldMiddleWareExtensionFilter>();
                return services;
            }
        }
        /// <summary>
        /// 在core的文档中的解析是如下
        /// 使用 Startup 筛选器扩展 Startup 使用 IStartupFilter
        /// 在应用的 Configure 中间件管道的开头或末尾配置中间件,而无需显式调用 Use{Middleware}。 IStartupFilter 由 ASP.NET Core 用于将默认值添加到管道的开头,而无需使应用作者显式注册默认中间件。 IStartupFilter 允许代表应用作者使用不同的组件调用 Use{Middleware}。
        ///创建 Configure 方法的管道。 IStartupFilter.Configure 可以将中间件设置为在库添加的中间件之前或之后运行。
        /// </summary>
        public class HellowWorldMiddleWareExtensionFilter : IStartupFilter
        {
            public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
            {
                return app =>
                {
                    app.UseMiddleware<HellowMiddleware>();
                    next(app);
                };
            }
        }
    }

    Startup代码如下

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using TestDoc.Infrastructure.Ex;
    using TestDoc.MiddleWare;
    
    namespace TestDoc
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                ///使用IStartupFilter对中间件的升级和扩展,这也是一半大牛自己写插件时候的逻辑
                ///直接注册服务即可,不必写配置管道,因为管道已经在注册服务已经配置管道了
                services.AddHellowWorldMiddleWareExtension();
                services.AddControllersWithViews();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

    这样我们就完美使用IStartupFilter 升级了中间件,core文档地址

    以上四种方法都可以用来学习管道和中间件的简单例子

     代码结构如下:

  • 相关阅读:
    [转]Git忽略规则及.gitignore规则不生效的解决办法
    动漫(杂)
    《计算机图形学》2.5 ~ 2.7 学习笔记
    《计算机图形学》2.4 输入设备 学习笔记
    《计算机图形学》2.2.2 光栅扫描显示处理器
    Android 使用版本控制工具时添加忽略文件方式
    devexpress表格控件gridcontrol设置隔行变色、焦点行颜色、设置(改变)显示值、固定列不移动(附源码)
    详解shape标签
    以向VS 程序打包集成自动写入注册表功能为例,介绍如何实现自由控制安装过程
    C#组件系列——又一款Excel处理神器Spire.XLS,你值得拥有
  • 原文地址:https://www.cnblogs.com/May-day/p/13087057.html
Copyright © 2011-2022 走看看