其他分享
首页 > 其他分享> > .NetCore中 Attributers、Filters以及中间件的使用

.NetCore中 Attributers、Filters以及中间件的使用

作者:互联网

Filters

Filters在.net core有一下几种:

执行顺序如下图:

各过滤器内方法执行流程如下:

AuthorizationFilter

认证过滤器的简单使用

    public class AuthorizationFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            Console.WriteLine($"{nameof(AuthorizationFilter)}:{nameof(OnAuthorization)}");
            if (!Authorization(context.HttpContext)) return;
        }
        private bool Authorization(HttpContext context)
        {
            if (1 != 1)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                _ = context.Response.WriteAsJsonAsync("Unauthorized");
                return false;
            }
            return true;
        }
    }
builder.Services.AddControllers(t =>
{
    t.Filters.Add<AuthorizationFilter>();
});

ResourceFilter

ResourceFilter 的简单应用

public class ResourceFilter : IResourceFilter
    {
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            Console.WriteLine($"{nameof(ResourceFilter)}:{nameof(OnResourceExecuted)}");
        }

        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            Console.WriteLine($"{nameof(ResourceFilter)}:{nameof(OnResourceExecuting)}");

            //对请求信息进行处理
            context.HttpContext.Request.Headers.TryAdd("CORE_HEADER", "123");
                       //Encoding.UTF8.GetString(buffer)
            context.HttpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(""));
        }
builder.Services.AddControllers(t =>
{
    t.Filters.Add<ResourceFilter>();
});

ActionFilter

public class ActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            Console.WriteLine($"{nameof(ActionFilter)}:{nameof(OnActionExecuted)}");
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Console.WriteLine($"{nameof(ActionFilter)}:{nameof(OnActionExecuting)}");
            //获得请求信息等
            var headers = context.HttpContext.Request.Headers;
        }

        public override void OnResultExecuted(ResultExecutedContext context)
        {
            Console.WriteLine($"{nameof(ActionFilter)}:{nameof(OnResultExecuted)}");
        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            Console.WriteLine($"{nameof(ActionFilter)}:{nameof(OnResultExecuting)}");
            //对返回的action结果进行处理
        }

    }
builder.Services.AddControllers(t =>
{
    t.Filters.Add<ActionFilter>();
});

ResultFilter

使用ResultFilter对返回结果进行重组

public class ResultFilter : ResultFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            Console.WriteLine($"{nameof(ResultFilter)}:{nameof(OnResultExecuted)}");
        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            Console.WriteLine($"{nameof(ResultFilter)}:{nameof(OnResultExecuted)}");
            //重写返回数据流
            //Encoding.UTF8.GetString(buffer)
            context.HttpContext.Response.Body = new MemoryStream(Encoding.UTF8.GetBytes(""));
        }
    }
builder.Services.AddControllers(t =>
{
    t.Filters.Add<ResultFilter>();
});

ExceptionFilter

ExceptionFilter捕获异常,并对其进行处理

 public class ExceptionFilter:ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            Console.WriteLine($"{nameof(ExceptionFilter)}:{nameof(OnException)}");
  			context.HttpContext.Response.Body= new MemoryStream(Encoding.UTF8.GetBytes(""));
            base.OnException(context);
        }
    }

Attributers

特性(Attributers )根据其自身创建时的约束,AttributeUsage特性 [AttributeUsage(AttributeTargets.Property| AttributeTargets.Class)] 标识可以用在哪些地方。

定义一个特性,使其只可在类和方法上使用

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class IPAttribute : Attribute
    {

        private readonly string _ip;

        public string IP
        {
            get { return _ip; }
        }
        public IPAttribute(string ip)
        {
            _ip = ip;
        }
        public bool CheckIP(string ip)
        {
            return !string.IsNullOrEmpty(ip);
        }
    }

将特性防止在接口方法上

 [IPAttribute("127.0.0.1")]
        [HttpGet("GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

在访问时对其进行校验

 public class AuthorizationFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            Console.WriteLine($"{nameof(AuthorizationFilter)}:{nameof(OnAuthorization)}");
            if (!Authorization(context.HttpContext)) return;
        }
        private bool Authorization(HttpContext context)
        {
            IPAttribute? authIP = context.GetEndpoint()?.Metadata?.GetMetadata<IPAttribute>();
            #region IP校验
            if (authIP != null && !CheckAttributeIP(authIP, context))
            {
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.Response.WriteAsync("IP Unauthorized").GetAwaiter();
                return false;
            }
            #endregion IP校验
            return true;
        }
        private static bool CheckAttributeIP(IPAttribute authIPAttribute, HttpContext context)
        {
            //获得客户端IP
            string clientIP = context.Connection.RemoteIpAddress.ToString();
            if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
                clientIP = context.Request.Headers["X-Forwarded-For"];
            if (string.IsNullOrEmpty(clientIP)) return false;
            return authIPAttribute.IP.Contains(clientIP);
            return false;
        }
    }

当访问IP不为127.0.0.1时,会返回401错误

Middleware

中间件是基于切面的一种组件

定义一个中间件,你可以在InvokeAsync中对context做任何操作

    public class RequestIPMiddleware
    {
        private readonly RequestDelegate _next;
        public RequestIPMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            Console.WriteLine("user IP:" + context.Connection?.RemoteIpAddress?.ToString());
            await _next.Invoke(context);
        }
    }

添加中间件

app.UseMiddleware<RequestIPMiddleware>();//添加中间件

标签:nameof,WriteLine,NetCore,中间件,Attributers,return,context,Console,public
来源: https://www.cnblogs.com/lostsea/p/16576169.html