0
点赞
收藏
分享

微信扫一扫

写一个五子棋小游戏

张宏涛心理 2024-03-22 阅读 13
.netcore

目录

.net Core 微服务接口增加过滤器实现预处理

1,过滤器的声明

2,过滤器的实现

3,过滤器中的扩展


接口增加过滤器实现预处理

1,过滤器的声明

人狠话不多,直接上代码

Startup.cs文件的ConfigureServices方法增加

   services.AddControllers(options =>
            {
                // 在这里添加你的过滤器
                options.Filters.Add(new InitializeRequestFilter());
            });

2,过滤器的实现

创建过滤器类InitializeRequestFilter

    public class InitializeRequestFilter : IActionFilter
    {
         
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //在请求动作执行前的代码
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // 如果需要,在动作执行后执行的代码
        }
    }

这样,在请求时会先执行OnActionExecuting,之后在执行OnActionExecuted

如果是重构的项目,可增加接口地址过滤,以下是例子

3,过滤器中的扩展

先定义一个地址列表(符合这个地址列表的地址才去执行过滤器)

   //自定义执行初始化的
        List<string> filterPaths = new List<string>() {
        "/domain/updateip", 
        };

这里优雅的使用一段linq实现地址列表过滤

     //符合filterPaths的path 执行此过滤器
            if (filterPaths.Select(p => p.ToLower()).ToList().Exists(x=>x== context.HttpContext.Request.Path.Value.ToLower()))
            {
                //这个仅仅是个 demo
                if (true)
                {
                    // 返回一个自定义的ActionResult,例如返回403 Forbidden
                    context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
                    return;
                }
            } 

linq不太好咱们就暴力一些,使用foreach

```csharp
// 将filterPaths中的路径转换为小写并存储在filterPathsLower列表中
var filterPathsLower = new List<string>();
foreach (var path in filterPaths)
{
    filterPathsLower.Add(path.ToLower());
}

// 检查请求路径是否存在于filterPathsLower列表中
bool pathExists = false;
foreach (var pathLower in filterPathsLower)
{
    if (pathLower == context.HttpContext.Request.Path.Value.ToLower())
    {
        pathExists = true;
        break;
    }
}

// 如果请求路径存在于filterPaths列表中
if (pathExists)
{
    // 这个仅仅是个 demo
    if (true)
    {
        // 返回一个自定义的ActionResult,例如返回403 Forbidden
        context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
        return;
    }
}
```
举报

相关推荐

0 条评论