• 一、模型验证CoreWebApi 管道方式(非过滤器处理)2(IApplicationBuilder扩展方法的另一种写法)


    一、 自定义中间件类的方式用一个单独类文件进行验证处理

    Configure下添加配置

                //app.AddAuthorize();
    AddAuthorize因为参数(this IApplicationBuilder applicationBuilder)来自IApplicationBuilder扩展方法
    using System;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace test.Controllers
    {
        public static class AuthorizeExtensio
        {
            public static void AddAuthorize(this IApplicationBuilder applicationBuilder)
            {
                applicationBuilder.Use(async (currentContext, nextContext) =>
                {
                    if (currentContext.Request.Headers.ContainsKey("Token"))
                    {
                        var authorize = currentContext.Request.Headers["Authorization"].ToString();
                        if (authorize.Contains("Basic"))//如果是Basic 身份认证
                        {
                            var info = authorize.Replace("Basic ", string.Empty);
                            var bytes = Convert.FromBase64String(info);//反解析Basic 64
                            var contents = Encoding.Default.GetString(bytes);
                            var dd = contents.Split(":").ToArray();
                            var userName = dd[0];//用户名
                            var userPwd = dd[1];//密码
                            if (userName == "GeBiLaoWang" && userPwd == "123456")
                            {
                                await currentContext.Response.WriteAsync("验证通过").ConfigureAwait(true); //Response.WriteAsync() 需要引用 Microsoft.AspNetCore.Http;
                                await nextContext?.Invoke();
                                return;
                            }
                        }
                    }
                    currentContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    await currentContext.Response.WriteAsync("See tou tomorrow!").ConfigureAwait(true);
                });
            }
        }
    }
  • 相关阅读:
    打印日志宏定义
    数据库读写操作
    SQL语句组成
    MySQL数据库的使用
    ubuntu下解决MySQL 1045 error
    css样式优先级
    redis
    dubbo
    maven
    Mybatis笔记
  • 原文地址:https://www.cnblogs.com/fger/p/11951839.html
Copyright © 2020-2023  润新知