/// <inheritdoc /> public async Task <StubModel> ConvertToStubAsync(OpenApiServer server, OpenApiLine line, string tenant) { var request = new HttpRequestModel { Body = _openApiDataFiller.BuildRequestBody(line.Operation), Headers = _openApiDataFiller.BuildRequestHeaders(line.Operation), Method = line.OperationType.ToString().ToUpper(), Url = $"{_openApiDataFiller.BuildServerUrl(server)}{_openApiDataFiller.BuildRelativeRequestPath(line.Operation, line.PathKey)}" }; var response = new HttpResponseModel { Content = _openApiDataFiller.BuildResponseBody(line.Response), Headers = _openApiDataFiller.BuildResponseHeaders(line.Response), StatusCode = _openApiDataFiller.BuildHttpStatusCode(line.ResponseKey) }; var stub = new StubModel { Tenant = tenant, Description = line.Operation.Summary, Conditions = await _httpRequestToConditionsService.ConvertToConditionsAsync(request), Response = await _httpResponseToStubResponseService.ConvertToResponseAsync(response), }; stub.EnsureStubId(); return(stub); }
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { OpenApiServer oaps = new OpenApiServer(); List <OpenApiServer> loaps = new List <OpenApiServer>() { oaps }; oaps.Url = @"http://10.172.18.146:8081/"; OpenApiPathItem oapi = new OpenApiPathItem() { Servers = loaps }; OpenApiPaths oap = new OpenApiPaths() { { "url", oapi } }; swaggerDoc.Paths = oap; //swaggerDoc.Servers //swaggerDoc.Host = "some-url-that-is-hosted-on-azure.azurewebsites.net"; //swaggerDoc.BasePath = "/api"; //swaggerDoc.Schemes = new List<string> { "https" }; }
private OAServer CreateAOServer(OpenApiServer s) { var server = new OAServer() { Description = s.Description, Url = s.Url, Variables = s.Variables.ToDictionary(v => v.Key, v => new OAServerVariable() { Name = v.Key, Description = v.Value.Description, Default = v.Value.Default, Enum = new List <string>(v.Value.Enum), Current = v.Value.Enum.IndexOf(v.Value.Default) }).Values.ToList(), }; server.Variables.ForEach(v => { v.Default = v.Default.Trim('/'); if (v.Enum.Count == 0) { v.Enum = new List <string> { v.Default }; } else { // trim all slashes for variants v.Enum = new List <string>(v.Enum.Select(e => e.Trim('/'))); } v.Current = 0; }); return(server); }
/// <inheritdoc /> public ISwaggerUI AddServer(HttpRequest req, string routePrefix, IOpenApiConfigurationOptions options = null) { var prefix = string.IsNullOrWhiteSpace(routePrefix) ? string.Empty : $"/{routePrefix}"; var baseUrl = $"{req.Scheme}://{req.Host}{prefix}"; if (options.IsNullOrDefault()) { this._baseUrl = baseUrl; return(this); } var server = new OpenApiServer { Url = baseUrl }; // Filters out the existing base URLs that are the same as the current host URL. var servers = options.Servers .Where(p => p.Url.TrimEnd('/') != baseUrl.TrimEnd('/')) .ToList(); servers.Insert(0, server); this._baseUrl = servers.First().Url; return(this); }
internal static OpenApiServer WithEndpointConfiguration(this OpenApiServer server, Action <XAmazonApiGatewayEndpointConfigurationOptions> setupAction) { var options = new XAmazonApiGatewayEndpointConfigurationOptions(); setupAction.Invoke(options); foreach (var item in options.ToDictionary()) { if (server.Extensions.ContainsKey(item.Key) && server.Extensions[item.Key] is OpenApiObject existingEndpointConfig) { if (item.Value is OpenApiObject existingConfigOptions) { foreach (var configOption in existingConfigOptions) { existingEndpointConfig[configOption.Key] = configOption.Value; } } } else { server.Extensions[item.Key] = item.Value; } } return(server); }
private static void MakeServers(IList <OpenApiServer> servers, ParsingContext context, Uri defaultUrl) { var host = context.GetFromTempStorage <string>("host"); var basePath = context.GetFromTempStorage <string>("basePath"); var schemes = context.GetFromTempStorage <List <string> >("schemes"); // If nothing is provided, don't create a server if (host == null && basePath == null && schemes == null) { return; } // Fill in missing information based on the defaultUrl if (defaultUrl != null) { host = host ?? defaultUrl.GetComponents(UriComponents.NormalizedHost, UriFormat.SafeUnescaped); basePath = basePath ?? defaultUrl.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped); schemes = schemes ?? new List <string> { defaultUrl.GetComponents(UriComponents.Scheme, UriFormat.SafeUnescaped) }; } else if (String.IsNullOrEmpty(host) && String.IsNullOrEmpty(basePath)) { return; // Can't make a server object out of just a Scheme } // Create the Server objects if (schemes != null && schemes.Count > 0) { foreach (var scheme in schemes) { var server = new OpenApiServer { Url = BuildUrl(scheme, host, basePath) }; servers.Add(server); } } else { var server = new OpenApiServer { Url = BuildUrl(null, host, basePath) }; servers.Add(server); } foreach (var server in servers) { // Server Urls are always appended to Paths and Paths must start with / // so removing the slash prevents a double slash. if (server.Url.EndsWith("/")) { server.Url = server.Url.Substring(0, server.Url.Length - 1); } } }
/// <summary> /// Visits <see cref="OpenApiServer"/> and child objects /// </summary> /// <param name="server"></param> internal void Walk(OpenApiServer server) { _visitor.Visit(server); foreach (var variable in server.Variables.Values) { Walk(variable); } _visitor.Visit(server as IOpenApiExtensible); }
public static OpenApiServer LoadServer(ParseNode node) { var mapNode = node.CheckMapNode("server"); var server = new OpenApiServer(); ParseMap(mapNode, server, _serverFixedFields, _serverPatternFields); return(server); }
static Uri GetUriFromServer(OpenApiServer server) { try { return(new Uri(server.Url)); } catch (UriFormatException) { return(null); } }
/// <summary> /// Visits <see cref="OpenApiServer"/> and child objects /// </summary> internal void Walk(OpenApiServer server) { if (server == null) { return; } _visitor.Visit(server); Walk(OpenApiConstants.Variables, () => Walk(server.Variables)); _visitor.Visit(server as IOpenApiExtensible); }
/// <summary> /// Specifies whether clients can invoke your API by using the default execute-api endpoint. By default, clients can invoke your API with the default https://{api_id}.execute-api.{region}.amazonaws.com endpoint. /// </summary> /// <param name="server"></param> /// <returns></returns> public static OpenApiServer DisableExecuteApiEndpoint(this OpenApiServer server) { return (server .WithEndpointConfiguration ( config => { config.DisableExecuteApiEndpoint = true; } )); }
internal static OpenApiServer WithEndpointConfiguration(this OpenApiServer server, Action <XAmazonApiGatewayEndpointConfigurationOptions> setupAction) { var options = new XAmazonApiGatewayEndpointConfigurationOptions(); setupAction.Invoke(options); foreach (var item in options.ToDictionary()) { server.Extensions[item.Key] = item.Value; } return(server); }
/// <summary> /// REGIONAL: For a regional API and its custom domain name. /// </summary> /// <param name="server"></param> /// <param name="customDomainName"></param> /// <returns></returns> public static OpenApiServer AsRegionalEndpoint(this OpenApiServer server, string customDomainName = null) { return (server .WithEndpointConfiguration ( config => { config.Types = new[] { "REGIONAL", customDomainName } .Where(x => !string.IsNullOrEmpty(x)); } )); }
/// <summary> /// PRIVATE: For a private API. /// </summary> /// <param name="server"></param> /// <param name="vpcEndpointIds"></param> /// <returns></returns> public static OpenApiServer AsPrivateEndpoint(this OpenApiServer server, params string[] vpcEndpointIds) { return (server .WithEndpointConfiguration ( config => { config.VpcEndpointIds = vpcEndpointIds.Where(x => !string.IsNullOrEmpty(x)); config.Types = new[] { "PRIVATE" }; } )); }
public void Traverse(OpenApiServer server) { if (server == null) { return; } Visitor.Visit(server); if (server.Variables != null) { foreach (var variable in server.Variables) { Traverse(variable.Value); } } }
private async Task <FullStubModel> CreateStub(bool doNotCreateStub, OpenApiServer server, OpenApiLine line, string tenant) { var stub = await _openApiToStubConverter.ConvertToStubAsync(server, line, tenant); if (doNotCreateStub) { return(new FullStubModel { Stub = stub, Metadata = new StubMetadataModel() }); } await _stubContext.DeleteStubAsync(stub.Id); return(await _stubContext.AddStubAsync(stub)); }
private static void MakeServers(IList <OpenApiServer> servers, ParsingContext context) { var host = context.GetFromTempStorage <string>("host"); var basePath = context.GetFromTempStorage <string>("basePath"); var schemes = context.GetFromTempStorage <List <string> >("schemes"); if (schemes != null) { foreach (var scheme in schemes) { var server = new OpenApiServer(); server.Url = scheme + "://" + (host ?? "example.org/") + (basePath ?? "/"); servers.Add(server); } } }
private string MapBasePath(IList <OpenApiServer> servers) { if (servers == null || servers.Count == 0) { return(string.Empty); } OpenApiServer server = servers.First(); Uri uriResult; if (Uri.TryCreate(server.Url, UriKind.RelativeOrAbsolute, out uriResult)) { return(uriResult.IsAbsoluteUri ? uriResult.AbsolutePath : uriResult.ToString()); } return(string.Empty); }
public void ValidateFieldIsRequiredInServer() { // Arrange IEnumerable <ValidationError> errors; OpenApiServer server = new OpenApiServer(); // Act var validator = new OpenApiValidator(); validator.Visit(server); errors = validator.Errors; bool result = !errors.Any(); // Assert Assert.False(result); Assert.NotNull(errors); ValidationError error = Assert.Single(errors); Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "url", "server"), error.ErrorMessage); }
/// <inheritdoc /> public IDocument AddServer(IHttpRequestDataObject req, string routePrefix, IOpenApiConfigurationOptions options = null) { this._req = req; var prefix = string.IsNullOrWhiteSpace(routePrefix) ? string.Empty : $"/{routePrefix}"; var baseUrl = $"{HttpRequestDataObjectExtensions.GetScheme(this._req, options)}://{this._req.Host}{prefix}"; var server = new OpenApiServer { Url = baseUrl }; if (GenericExtensions.IsNullOrDefault(options)) { this.OpenApiDocument.Servers = new List <OpenApiServer>() { server }; return(this); } // Filters out the existing base URLs that are the same as the current host URL. var servers = options.Servers .Where(p => p.Url.TrimEnd('/') != baseUrl.TrimEnd('/')) .ToList(); if (!servers.Any()) { servers.Insert(0, server); } if (options.IncludeRequestingHostName && !servers.Any(p => p.Url.TrimEnd('/') == baseUrl.TrimEnd('/'))) { servers.Insert(0, server); } this.OpenApiDocument.Servers = servers; return(this); }
private static Uri ParseBaseUri(Uri baseUri, OpenApiServer openApiServer) { if (openApiServer != null) { Uri tempUri; try { tempUri = new Uri(openApiServer.Url, UriKind.RelativeOrAbsolute); } catch (Exception) { tempUri = baseUri; } if (tempUri.IsAbsoluteUri) { baseUri = tempUri; } else { if (baseUri == null) { throw new QAToolKitSwaggerException( "Swagger needs BaseUrl defined. Inject baseUrl with AddBaseUrl in your SwaggerSource instantiation."); } baseUri = new Uri(baseUri, tempUri); } } else { if (baseUri == null) { throw new QAToolKitSwaggerException( "Swagger needs BaseUrl defined. Inject baseUrl with AddBaseUrl in your SwaggerSource instantiation."); } } return(baseUri); }
/// <inheritdoc /> public ISwaggerUI AddServer(IHttpRequestDataObject req, string routePrefix, IOpenApiConfigurationOptions options = null) { this._req = req; var prefix = string.IsNullOrWhiteSpace(routePrefix) ? string.Empty : $"/{routePrefix}"; var baseUrl = $"{this._req.GetScheme(options)}://{this._req.Host}{prefix}"; this._swaggerUiApiPrefix = prefix.TrimEnd('/'); if (options.IsNullOrDefault()) { this._baseUrl = baseUrl; return(this); } var server = new OpenApiServer { Url = baseUrl }; // Filters out the existing base URLs that are the same as the current host URL. var servers = options.Servers .Where(p => p.Url.TrimEnd('/') != baseUrl.TrimEnd('/')) .ToList(); if (!servers.Any()) { servers.Insert(0, server); } if (options.IncludeRequestingHostName && !servers.Any(p => p.Url.TrimEnd('/') == baseUrl.TrimEnd('/'))) { servers.Insert(0, server); } this._baseUrl = servers.First().Url; return(this); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSwagger(c => { c.PreSerializeFilters.Add((swaggerDoc, httpReq) => { var paths = new OpenApiPaths(); foreach (var path in swaggerDoc.Paths) { paths.Add(BasePath + path.Key, path.Value); } swaggerDoc.Paths = paths; var servers = new OpenApiServer { Url = httpReq.Host + BasePath, }; swaggerDoc.Servers.Add(servers); }); }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swashbuckle Test API V1"); }); }
/// <summary> /// Provide specific server information to include in the generated Swagger document /// </summary> /// <param name="swaggerGenOptions"></param> /// <param name="server">A description of the server</param> public static void AddServer(this SwaggerGenOptions swaggerGenOptions, OpenApiServer server) { swaggerGenOptions.SwaggerGeneratorOptions.Servers.Add(server); }
/// <summary> /// Visits <see cref="OpenApiServer"/> /// </summary> public virtual void Visit(OpenApiServer server) { }
/// <summary> /// Convenience extension method for adding a variable to a server instance /// </summary> /// <param name="server">The server that will receive the new variable</param> /// <param name="key">The variable name (e.g. basePath)</param> /// <param name="value">The value for the variable</param> /// <returns></returns> public static OpenApiServer WithVariable(this OpenApiServer server, string key, OpenApiServerVariable value) { server.Variables.Add(key, value); return(server); }
/// <summary> /// 配置 /// </summary> /// <param name="context"></param> public override void ConfigureServices(ServiceConfigurationContext context) { //配置Swagger; var basePath = Path.GetDirectoryName(typeof(CSumAbpSwaggerUIModule).Assembly.Location); var groupOptionsLazy = context.Services.GetRequiredServiceLazy <IOptions <AbpModuleApiGroupOptions> >(); Configure <SwaggerGenOptions>(c => { var groupOptions = (groupOptionsLazy.Value).Value; //为 Swagger 添加 Bearer Token 认证 c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer", BearerFormat = "JWT", }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference() { Id = "Bearer", //这个名称必须和上方定义的名称一致 Type = ReferenceType.SecurityScheme } }, Array.Empty <string>() } }); c.IgnoreObsoleteActions(); //忽略已过时api //增加服务端 必须得有 var local = new OpenApiServer() { Url = "", Description = "本地系统" }; c.AddServer(local); //自定义操作id 必须得有 c.CustomOperationIds(apiDesc => { var controllerAction = apiDesc.ActionDescriptor as ControllerActionDescriptor; return(controllerAction.ControllerName + "-" + controllerAction.ActionName); }); //加载分组 foreach (var group in groupOptions.Groups) { c.SwaggerDoc(group.Name, new OpenApiInfo { Title = group.Title, Version = group.Name }); } //加载xml foreach (var xmlname in groupOptions.XmlDocuments) { var apiXmlPath = Path.Combine(basePath, $"{xmlname}.xml"); if (File.Exists(apiXmlPath)) { c.IncludeXmlComments(apiXmlPath, true); } } }); }
/// <summary> /// Execute validation rules against an <see cref="OpenApiServer"/> /// </summary> /// <param name="item">The object to be validated</param> public override void Visit(OpenApiServer item) => Validate(item);
public override void Visit(OpenApiServer server) { EncodeCall(); base.Visit(server); }
public override void Visit(OpenApiServer server) { Locations.Add(this.PathString); }