雪花

一、模型验证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);
            });
        }
    }
}

 

posted @ 2019-11-28 18:04  十色  阅读(561)  评论(0编辑  收藏  举报