有2个过滤扣 IActionFilter 接口和ActionFilterAttribute特性
1、继承接口可以直接用void形成基类,在动态api中继承使用,实例代码如下
public class FilterBase : IActionFilter, IDynamicApiController
{
public SqlSugar.SqlSugarClient DB = SqlSugarUse.CreateSqlServer();
public TokenModel tokenModel =new TokenModel();
[ApiExplorerSettings(IgnoreApi = true)]
public void OnActionExecuted(ActionExecutedContext context)
{
}
[ApiExplorerSettings(IgnoreApi = true)]
public void OnActionExecuting(ActionExecutingContext context)
{
var JwtToken =App.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ","");
if (string.IsNullOrWhiteSpace(JwtToken))
{
context.Result = new ContentResult() { Content = "TokenOut", StatusCode = 499 };
//context.Result = Redirect("~/Manager/Index.html");
}
else
{
var myclaims = JWTEncryption.ReadJwtToken(JwtToken)?.Claims;
tokenModel.UserId = myclaims.FirstOrDefault(t => t.Type == "UserId")?.Value;
tokenModel.Account = myclaims.FirstOrDefault(t => t.Type == "Account")?.Value;
tokenModel.Rolelist = myclaims.FirstOrDefault(t => t.Type == "Rolelist")?.Value;
}
}
2、继承特性可以在方法中直接标注特性使用
public class FilterBaseAttribute : ActionFilterAttribute
{
public SqlSugar.SqlSugarClient DB = SqlSugarUse.CreateSqlServer();
public TokenModel tokenModel =new TokenModel();
[ApiExplorerSettings(IgnoreApi = true)]
public override void OnActionExecuted(ActionExecutedContext context)
{
}
[ApiExplorerSettings(IgnoreApi = true)]
public override void OnActionExecuting(ActionExecutingContext context)
{
var JwtToken =App.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ","");
if (string.IsNullOrWhiteSpace(JwtToken))
{
context.Result = new ContentResult() { Content = "{Code:200,Msg:'TokenOut'}", StatusCode = 499 };
//context.Result = Redirect("~/Manager/Index.html");
}
else
{
LoginModelStatic.LoginId = 2;
var myclaims = JWTEncryption.ReadJwtToken(JwtToken)?.Claims;
tokenModel.UserId = myclaims.FirstOrDefault(t => t.Type == "UserId")?.Value;
tokenModel.Account = myclaims.FirstOrDefault(t => t.Type == "Account")?.Value;
tokenModel.Rolelist = myclaims.FirstOrDefault(t => t.Type == "Rolelist")?.Value;
}
}
}
注意,继承 IActionFilter接口,可以直接使用 [ApiExplorerSettings(IgnoreApi = true)] 特性,控制在swagger中的显示