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文档地址

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

     代码结构如下:

  • 相关阅读:
    获取Tekla属性方式
    基于C# 百度AI和科大汛飞语音合成SDK
    BIM工程信息管理系统-EF实体框架数据操作基类
    BIM工程信息管理新系统- 系统管理模块
    EChart绘制风速风向曲线分析图
    BIM工程信息管理系统-详细设计
    BIM工程信息管理系统搭建-系统功能需求
    基于C# 调用百度AI 人脸识别
    mago3DJS 应用
    Bitnami redmine windows环境下升级
  • 原文地址:https://www.cnblogs.com/May-day/p/13087057.html
Copyright © 2011-2022 走看看