Beispiel #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            var openApiDoc = OpenApiDocumentReaderHelper.GetOpenApiDocument(_environment.WebRootPath);

            var ruleEngineBuilder           = new OpenApiValidatorBuilder(new ValidatorContext());
            var ruleEngineRequestValidators = new SortedDictionary <string, OpenApiHttpRequestValidator>();

            ruleEngineBuilder.Build(openApiDoc).Cast <OpenApiHttpRequestValidator>().ToList().ForEach(e => ruleEngineRequestValidators.Add(e.Key, e));
            var dummyValidator = new OpenApiHttpRequestValidator();

            services.AddTransient <OpenApiHttpRequestValidator, OpenApiHttpRequestValidator>((provider) =>
            {
                var request          = provider.GetRequiredService <IHttpContextAccessor>().HttpContext.Request;
                var requestValidator = ruleEngineRequestValidators.FirstOrDefault(e => e.Key.ToLower() == $"{request.Path}{request.Method}".ToLower().Replace("/", ""));              // request.Method);

                if (requestValidator.Key != null)
                {
                    return((OpenApiHttpRequestValidator)requestValidator.Value.Clone());
                }

                return(dummyValidator);
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Beispiel #2
0
        public async Task Invoke(HttpContext httpContext, OpenApiHttpRequestValidator _httpRequestValidator)
        {
            if (_httpRequestValidator.UrlPath == null)
            {
                await _next(httpContext);
            }
            else
            {
                var logs = _httpRequestValidator.Validate(httpContext);

                if (logs.Count == 0)
                {
                    await _next(httpContext);
                }
                else
                {
                    httpContext.Response.ContentType = "application/json";
                    var response = new ApiResponse(httpContext.Response.StatusCode, logs);
                    var json     = JsonConvert.SerializeObject(response);
                    await httpContext.Response.WriteAsync(json);
                }
            }
        }