一、WebAuthorize 1、项目名称 WebAuthorize 2、加个中间件 过滤请求。 using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Net; u
一、WebAuthorize
1、项目名称 WebAuthorize
2、加个中间件 过滤请求。
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 WebAuthorize { public static class AuthorizeExtensio { public static void AddAuthorize(this IApplicationBuilder applicationBuilder) { applicationBuilder.Use(async (currentContext, nextContext) => { if (currentContext.Request.Headers.ContainsKey("Authorization")) { 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); }); } } }
3、修改配置文件
//添加服务 app.AddAuthorize(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!").ConfigureAwait(true); });