.NET6自定義WebAPI過濾器
更新時(shí)間:2021年12月24日 08:47:11 作者:PrintY
這篇文章介紹了.NET6自定義WebAPI過濾器的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
1、上代碼
/// <summary> /// API白名單過濾器 /// </summary> public class APIFilter : ActionFilterAttribute { /// <summary> /// 控制器中加了該屬性的方法中代碼執(zhí)行之前該方法。 /// 所以可以用做權(quán)限校驗(yà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í)行完成后才會(huì)來執(zhí)行該方法。 /// </summary> /// <param name="context"></param> public override void OnActionExecuted(ActionExecutedContext context) { base.OnActionExecuted(context); } /// <summary> /// 控制器中加了該屬性的方法執(zhí)行完成后才會(huì)來執(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
到此這篇關(guān)于.NET6自定義WebAPI過濾器的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
asp.net BackgroundWorker之在后臺(tái)下載文件
下載文件是常見任務(wù),通常情況下,最好以單獨(dú)的線程來運(yùn)行這項(xiàng)可能很耗時(shí)的操作。使用 BackgroundWorker 組件可以用非常少的代碼完成此任務(wù)2011-12-12asp.net request.PathInfo實(shí)現(xiàn)的url重寫
最近對(duì)在開始研究url重寫,對(duì)重寫的原理以及重寫之后引起的性能問題是研究的重點(diǎn),研究過程中發(fā)現(xiàn)了一種輕便的“url重寫方案”2009-04-04asp.net點(diǎn)選驗(yàn)證碼實(shí)現(xiàn)思路分享 (附demo)
這篇文章主要介紹了asp.net點(diǎn)選驗(yàn)證碼實(shí)現(xiàn)思路分享 (附demo),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-01-01Asp.net開發(fā)常用的51個(gè)非常實(shí)用的代碼
Asp.net開發(fā)常用的51個(gè)非常實(shí)用的代碼,需要的朋友可以參考下。2010-06-06asp.net 站點(diǎn)URLRewrite使用小記
asp.net的底層運(yùn)作已經(jīng)也亂談過一番, 今天記一下URLRewrite的方法。2009-11-11