如何判断当前请求的API类型
生活随笔
收集整理的這篇文章主要介紹了
如何判断当前请求的API类型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
上次,我們判斷了《當前請求是否健康檢查API》,避免其寫入日志。
但是,對于我們自己開發的API來說,最好也能來區分,比如調試用API,就不需要再寫調用日志了。
DisplayName方式
直接判斷路由地址的方式就不考慮了。
本來想使用和上次一樣的DisplayName方式,但是發現沒有地方為Controller設置。
查看源碼,發現Action的DisplayName屬性的實現在ControllerActionDescriptor.cs:
public?override?string??DisplayName {get{if?(base.DisplayName?==?null?&&?ControllerTypeInfo?!=?null?&&?MethodInfo?!=?null){base.DisplayName?=?string.Format(CultureInfo.InvariantCulture,"{0}.{1}?({2})",TypeNameHelper.GetTypeDisplayName(ControllerTypeInfo),MethodInfo.Name,ControllerTypeInfo.Assembly.GetName().Name);}return?base.DisplayName!;}set{if?(value?==?null){throw?new?ArgumentNullException(nameof(value));}base.DisplayName?=?value;} }DisplayName是由"Controller類名.方法名 (Assembly名)"組成。
如果你的Controller類名/方法名命名有規律,可以考慮DisplayName方式。
Metadata方式
此路不通,考慮其他方式。
我們知道將Controller的方法添加為API端點是通過endpoints.MapControllers();,查看其實現源碼,最終定位到ActionEndpointFactory.cs,其中有這樣一段代碼:
//?MVC?guarantees?that?when?two?of?it's?endpoints?have?the?same?route?name?they?are?equivalent.? //? //?The?case?for?this?looks?like:? //? //?[HttpGet]? //?[HttpPost]? //?[Route("/Foo",?Name?=?"Foo")]? //?public?void?DoStuff()?{?}? //? //?However,?Endpoint?Routing?requires?Endpoint?Names?to?be?unique.? //? //?We?can?use?the?route?name?as?the?endpoint?name?if?it's?not?set.?Note?that?there's?no? //?attribute?for?this?today?so?it's?unlikley.?Using?endpoint?name?on?a? if?(routeName?!=?null?&&? !suppressLinkGeneration?&&? routeNames.Add(routeName)?&&? builder.Metadata.OfType<IEndpointNameMetadata>().LastOrDefault()?.EndpointName?==?null)? {? builder.Metadata.Add(new?EndpointNameMetadata(routeName));? }通過注釋,我們可以知道Asp.Net Core會把RouteName寫入端點的Metadata屬性。
那么,我們只需要判斷EndpointNameMetadata即可:
var?endpointName?=?context.GetEndpoint()?.Metadata.GetMetadata<EndpointNameMetadata>()?.EndpointName; if?(!string.IsNullOrEmpty(endpointName)?&&?endpointName.StartsWith("Debug_")) { } else {//Log }結論
如果你有更好的實現方式,歡迎到公眾號后臺留言告訴我。
總結
以上是生活随笔為你收集整理的如何判断当前请求的API类型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: YARP+AgileConfig 5分钟
- 下一篇: CALL FOR DUTY 来和我们一起