public async Task Invoke(HttpContext context) { // Check is request to Swagger if (!SwaggerHelper.IsAccessSwagger(context, _options)) { await _next.Invoke(context).ConfigureAwait(true); return; } // Set cookie if need string requestAccessKey = context.Request.Query[ElectSwaggerConstants.AccessKeyName]; if (!string.IsNullOrWhiteSpace(requestAccessKey) && context.Request.Cookies[ElectSwaggerConstants.AccessKeyName] != requestAccessKey) { SetCookie(context, ElectSwaggerConstants.CookieAccessKeyName, requestAccessKey); } // Check Permission bool isCanAccess = SwaggerHelper.IsCanAccessSwagger(context, _options.AccessKey); if (!isCanAccess) { context.Response.StatusCode = StatusCodes.Status403Forbidden; await context.Response.WriteAsync(_options.UnAuthorizeMessage).ConfigureAwait(true); return; } if (SwaggerHelper.IsAccessJsonViewer(context, _options)) { var jsonViewerContentResult = SwaggerHelper.GetApiJsonViewerHtml(); context.Response.ContentType = jsonViewerContentResult.ContentType; context.Response.StatusCode = jsonViewerContentResult.StatusCode ?? StatusCodes.Status200OK; await context.Response.WriteAsync(jsonViewerContentResult.Content, Encoding.UTF8).ConfigureAwait(true); return; } if (SwaggerHelper.IsAccessUI(context, _options)) { var apiDocContentResult = SwaggerHelper.GetApiDocHtml(); context.Response.ContentType = apiDocContentResult.ContentType; context.Response.StatusCode = apiDocContentResult.StatusCode ?? StatusCodes.Status200OK; await context.Response.WriteAsync(apiDocContentResult.Content, Encoding.UTF8).ConfigureAwait(true); return; } // Next middleware is swagger endpoint => generate document by swagger await _next.Invoke(context).ConfigureAwait(true); }