.net core 中间件控制用户访问

1:新建 【中间件】类

public class HttpContextMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

public HttpContextMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<HttpContextMiddleware>();
}
/// <summary>
/// 异常返回信息
/// </summary>
/// <param name="context"></param>
/// <param name="exception"></param>
/// <returns></returns>
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var response = context.Response;
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
await response.WriteAsync(JsonConvert.SerializeObject(new
{
// customize as you need
error = new
{
message = exception.Message,
exception = exception.GetType().Name
}
}));
#region MyRegion
// if (e is UnauthorizedAccessException)
// context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
// else if (e is Exception)
// context.Response.StatusCode = (int)HttpStatusCode.BadRequest;

// context.Response.ContentType = "application/json";

// await context.Response.WriteAsync(
// JsonConvert.SerializeObject(
// ReturnVerify.ReturnError("", e.GetBaseException().Message))).ConfigureAwait(false);
//}
#endregion
}
/// <summary>
/// 拦截调用
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public async Task Invoke(HttpContext httpContext)
{
httpContext.Request.EnableBuffering();
try
{

// 获取jwtToken
var jwtobj = ToolHelp.GetJson(httpContext.Request.Headers["Authorization"].ToString());
if (jwtobj != null)
{

// 检测用户是否可以访问
var str = CustomerSql.GetRoleApiNamebyUserId(jwtobj.Id, httpContext.Request.Path);
if (str == null)
{
await ReturnObj(httpContext);
}
else
{
await _next.Invoke(httpContext);
}
}
else
{
await ReturnObj(httpContext);
}
}
catch (Exception e)
{
await HandleExceptionAsync(httpContext, e);
// return Task.CompletedTask;
}
}

/// <summary>
/// 授权异常
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public async Task ReturnObj(HttpContext httpContext)
{
httpContext.Response.Clear();
httpContext.Response.ContentType = "application/json";
httpContext.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new
{

// customize as you need

result = new
{
code = 405,
msg = "未授权",
data = false
},
targetUrl = "null",
success = false,
error = "未授权",
unAuthorizedRequest = false,
__abp = true
}));
}
}

/// <summary>
/// 把Json文本转为实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="input"></param>
/// <returns></returns>
public static JwtJsonObj GetJson(string input)
{
try
{
byte[] c = Convert.FromBase64String(input.Split('.')[1]);
var a = System.Text.Encoding.Default.GetString(c);
return JsonConvert.DeserializeObject<JwtJsonObj>(a);
}
catch (Exception ex)
{
return default(JwtJsonObj);
}
}

 

 2:在Startup===Configure 中注入使用

 

posted @   两台显示器的人生  阅读(374)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示