.Net Core 建立和使用中間件

1. 定義中間內容app

1.1 必須有一個RequestDelegate 委託用了進入一箇中間件函數

1.2 經過構造函數設置這個RequestDelegate委託ui

1.3 必須有一個方法Task Invoke,在這個方法裏編寫中間件內容最後執行RequestDelegate委託this

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. 編寫一個擴展方法用來添加到程序中spa

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添加中間件code

// 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();
            });
        }
相關文章
相關標籤/搜索