使用NLog给Asp.Net Core做请求监控的方法(4)

/// <summary> /// 验证请求用户是否已经认证 /// </summary> public interface IRequestIsAuthenticate { /// <summary> /// 返回已经认证的 scheme /// </summary> /// <returns></returns> Task<string> IsAuthenticateAsync(); /// <summary> /// 返回已经认证的 用户名 /// </summary> /// <returns></returns> Task<string> AuthenticatedUserName(); }

就验证而言可能不同的开发者使用的是不一样的验证方式,可能是基于 Asp.Net Core Authentication 中间件的认证方式,也可能是其他的比如自定义的 token,或者有一个单点登录的服务器,又或者是 session,其实 Asp.Net Core 的 Authentication 中间件也可以帮我们实现基于 restful 的token 认证。所以就把它定义出来了,并且默认的实现就是基于 Authentication 这个中间件的。

IStartupFilter

看到他是一个非常特殊的方式来注册的,自定义的 FirstRegister 这个方法,实际上 Asp.Net Core 内置有多个 IStartup 这样的服务,并且都是在 Startup 的 Configure 之前执行的,所以这里一定要用这个服务来让我们的中间件成为第一个中间件。FirstRegister 代码也很容易理解,由于在宿主启动之前,内部注册了多个 IStartup,并且最后会按先后顺序配置 IApplicationBuilder,所以我们只能让第一个 StartupFilter 的 IApplicationBuilder 就注册我们的中间件,通过改动 ServiceCollection 中服务的顺序可以实现。虽然不是很有必要,但是可以从中观察的 Startup 的 Configure方法 以及 接口StartupFilter (还有 IHostingStartup )的执行顺序。

public class RequestApiInsightBeginStartupFilter : IStartupFilter { public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) { return builder => { builder.UseMiddleware<RequestApiInsightBeginMiddleware>(); next(builder); }; } }

忽略的方法

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class NoInsightAttribute : Attribute { }

在 ApiInsight 方法中会调用 IsIgnore 检测该方法是否打了标签 NoInsightAttribute,如果是那就忽略该方法,这里建议使用特性路由,原因有两点,第一特性路由不需要使用 IActionSelector 接口重新查找匹配的方法,第二,在 restful api 中,结合特性路由和 HttpMethodAttribute 标签可以使方法更简洁,相同的接口名称通过不同的请求方式达到不同的目的

private bool IsIgnore() { var actionDescriptor = GetSelectedActionDescriptor() as ControllerActionDescriptor; if (actionDescriptor == null) { return false; } else { var noInsight = actionDescriptor.MethodInfo.GetCustomAttribute<NoInsightAttribute>(); return noInsight != null; } }

程序地址: https://github.com/cheesebar/ApiInsights

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdssyp.html