.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();
            });
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM