日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

.NET6自定義WebAPI過濾器_實用技巧

作者:PrintY ? 更新時間: 2022-03-16 編程語言

1、上代碼

/// <summary>
    /// API白名單過濾器
    /// </summary>
    public class APIFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 控制器中加了該屬性的方法中代碼執(zhí)行之前該方法。
        /// 所以可以用做權(quán)限校驗。
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var vistorIp = context.HttpContext.Connection.RemoteIpAddress.ToString_();
            var whiteIp = AppsettingHelper.Get("WhiteIP");
            if (!string.IsNullOrEmpty(whiteIp))
            {
                List<string> whiteIpList = whiteIp.Split(',').ToList();
                if (!whiteIpList.Contains("*") && !whiteIpList.Contains(vistorIp))
                {
                    context.HttpContext.Response.StatusCode = 401;
                    context.Result = new JsonResult(new { code = 401, msg = "非法IP" });
                }
            }
            base.OnActionExecuting(context);
        }
        /// <summary>
        /// 控制器中加了該屬性的方法執(zhí)行完成后才會來執(zhí)行該方法。
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
        }
        /// <summary>
        /// 控制器中加了該屬性的方法執(zhí)行完成后才會來執(zhí)行該方法。比OnActionExecuted()方法還晚執(zhí)行。
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            return base.OnResultExecutionAsync(context, next);
        }
    }

2、使用

    [Route("api/[controller]/[action]")]
    [ApiController]
    [APIFilter]
    public class YangController : BaseController

原文鏈接:https://www.cnblogs.com/PrintY/p/15666986.html

欄目分類
最近更新