ASP.NET Core HTTP 管道

中间件
*
*
IApplicationBuilder
*
RequestDelegate 管道
RequestDelegate 是一个委托,它代表一项请求处理任务,是以委托形式对 HttpContext 的封装
*
HttpContext
*
HttpRequest
*
HttpResponse
*
*
*
*
*
*
Startup.cs

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseExceptionHandler("/Home/Error");
         app.UseHsts();
     }

     app.UseHttpsRedirection();

     #region 中间件

     //app.UseMiddleware<AdminSafeListMiddleware>(Configuration["AdminSafeList"]);
     app.UseMiddleware<AuthorizeMiddleware>();

     app.Use(async (context, next) =>
     {
         await context.Response.WriteAsync("Hello World 1");
         await next();
     });

     app.Run(async (context) =>
     {
         await context.Response.WriteAsync("Hello World 2");
     });

     #endregion

     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
     });
 }

HTTP 管道中间件

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

namespace AuthService
{
    public class AuthorizeMiddleware
    {
        private readonly RequestDelegate _next;

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

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next.Invoke(context);
            }
            catch (Exception ex)
            {
                var statusCode = context.Response.StatusCode;
            }
            finally
            {
                var statusCode = context.Response.StatusCode;
                var msg = String.Empty;
                if (statusCode == 400)
                {
                    await HandleExceptionAsync(context, statusCode, "");
                }
                else if (statusCode == 401)
                {
                    context.Response.OnStarting(state =>
                    {
                        var httpContext = (HttpContext)state;
                        httpContext.Response.Headers.Add("test2", "testvalue2");
                        httpContext.Response.StatusCode = 401;
                        httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { code = "401", msg = "Unauthorized" }));
                        return Task.FromResult(0);
                    }, context);
                }
            }
            await _next(context);
        }

        private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
        {
            return context.Response.WriteAsync(JsonConvert.SerializeObject(new { code = "401", msg = "Unauthorized" }));
        }
    }
}

*
*
*
*
*
*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值