• .Net Core 创建和使用中间件


    1. 定义中间内容

    1.1 必须有一个RequestDelegate 委托用了进入一个中间件

    1.2 通过构造函数设置这个RequestDelegate委托

    1.3 必须有一个方法Task Invoke,在这个方法里编写中间件内容最后执行RequestDelegate委托

    using Microsoft.AspNetCore.Http;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Haos.Develop.CoreTest
    {
        public class TestMiddleware
        {
            protected RequestDelegate Next;
    
            /// <summary>
            /// 参数
            /// </summary>
            public string Str { get; set; }
    
            public TestMiddleware(RequestDelegate next,string s)
            {
                Next = next;
                Str = s;
            }
    
            public virtual Task Invoke(HttpContext context)
            {
                context.Response.WriteAsync("this is test string");
                return Next(context);
            }
        }
    }

    2. 编写一个扩展方法用来添加到程序中

    using Haos.Develop.CoreTest.Service;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.Extensions.DependencyInjection;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Haos.Develop.CoreTest
    {
        public static class Extension
        {
            public static IApplicationBuilder UserTestMiddleWare(this IApplicationBuilder app, string str)
            {
                return app.UseMiddleware<TestMiddleware>(str);
            }
        }
    }

    3.  在Startup添加中间件

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                //扩展方式添加
                app.UserTestMiddleWare("this is test param");
                //直接添加中间件方式
                app.Use((context, next) =>
                {
                    context.Response.WriteAsync("this is test");
                    return next();
                });
            }
  • 相关阅读:
    Skyline软件SFS服务介绍
    选择三维地理信息系统(GIS)软件平台需要考虑的内容
    如何利用Skyline6.1的接口创建动态对象DynamicObject
    Skyline中的隐藏组
    基于Skyline的TerraExplorer6.1.1如何通过二次开发实现折线和多边形对象的手动绘制
    如何利用Skyline6.1实现多球对比功能
    Skyline for Android & iOS devices
    VBS、WKT、投影
    FME+Oracle Spatial+SFS+TEPro
    如何生成静态页
  • 原文地址:https://www.cnblogs.com/haosit/p/7754257.html
Copyright © 2020-2023  润新知