.net core2.0 自定義中間件

1、中間件(Middleware)

  中間件是被組裝成一個應用程序管道來處理請求和響應的軟件組件。async

  

2、編寫SimpleMiddleware

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GrabNovelApi.MiddleWare
{
    public class SimpleMiddleWare
    {
        private readonly RequestDelegate _next;

        public SimpleMiddleWare(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {

            Console.WriteLine("invoke");
            await _next.Invoke(context);
        }
    }
}

3、再新建一個:SimpleMiddleWareExtensions.cs

  用起來總有點奇怪,竟然不是繼承一個基類ui

using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GrabNovelApi.MiddleWare
{
    public static class SimpleMiddleWareExtensions
    {
        public static IApplicationBuilder SimpleMiddleWare(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<SimpleMiddleWare>();
        }
    }
}

4、使用中間件

  

相關文章
相關標籤/搜索