pictureServer/PictureFilesApi/Common/CustomActionFilter.cs

66 lines
2.0 KiB
C#
Raw Normal View History

2026-03-10 09:04:34 +08:00
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using LongHuParkApi.Common;
using LongHuParkApi.Models;
namespace LongHuParkApi.Common
{
public class CustomActionFilter : IActionFilter
{
//添加过滤器
public void OnActionExecuting(ActionExecutingContext context)
{
// Action执行之前
//判断是否存在AllowAnonymousAttribute属性
var count = context.ActionDescriptor.EndpointMetadata.Where(c => c.GetType().Name == "AllowAnonymousAttribute").Count();
if(count == 0)
{
//开始验证token是否有效
var token = context.HttpContext.Request.Headers["token"].ToString();
//是否验证成功
bool? success = null;
if (string.IsNullOrEmpty(token))
{
success = false;
}
else
{
var userInfo = CacheHelper.GetCache<UserInfo>(token);
if (userInfo == null)
{
success = false;
}
}
if(success == false)
{
//如果无效,返回错误信息
var result = new JsonResult("权限验证失败");
result.StatusCode = (int)HttpStatusCode.BadRequest;
context.Result = result;
}
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
//Action执行之后
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
// Action执行之前
await next();
// Action执行之后
}
}
}