拦截器
登录拦截器 继承ActionFilterAttribute
分为在请求接口前拦截与请求接口后拦截
接口连接前拦截 重写(OnActionExecuting)
public override void OnActionExecuting(ActionExecutingContext context)
{
Debug.WriteLine("拦截之前");
//获取请求的路径
string path = context.HttpContext.Request.Path;
Debug.WriteLine("请求路径:" + path);
//当路径是请求登录的时候,就不用拦截
if(path != "/baseUser/login")
{
//context.HttpContext.Request.Headers["token"]; //一般token回放在请求头里面
object? tokenObj = context.ActionArguments["token"];
if (tokenObj == null || string.IsNullOrEmpty(tokenObj.ToString()))
{
context.Result = new JsonResult(WebApiResponse.Create(1, "非法登录"));
}
else
{
//登录时返回的token值
string token = tokenObj.ToString();
int userId = UserData.GetIdByToken(token);
if (userId == -1)
{
//直接返回一个结果,修改请求的返回值,请求接口的方法不会去执行,拦截之后的方法也不会去执行
context.Result = new JsonResult(WebApiResponse.Create(2, "请重新登录"));
return;
}
//查询人员信息
BaseUser user = UserData.GetUserById(userId);
if (user == null)
{
context.Result = new JsonResult(WebApiResponse.Create(3, "用户不存在"));
return;
}
//判断是否黑户
if (user.TStatus == "1")
{
context.Result = new JsonResult(WebApiResponse.Create(4, "您已被拉黑,请联系管理员"));
return;
}
}
}
}
接口连接后拦截 重写(OnActionExecuted)
// <summary>
/// 在请求接口方法之后拦截
/// </summary>
/// <param name="context"></param>
public override void OnActionExecuted(ActionExecutedContext context)
{
Debug.WriteLine("拦截之后");
}
[拦截器类名字]
放在类的前面,对整个类生效
放在方法的前面只对这一个方法生效
//拦截所有接口
builder.Services.AddMvc(optipns =>
{
//FactoryFillter 拦截器类名
optipns.Filters.Add<FactoryFillter>();
});
在program中添加此行代码,会拦截所有接口
builder.Services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
});
在program中添加此行代码,会处理前后端数据交互出现乱码的情况