.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 中注入使用