Explore all Swagger open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Swagger

fastapi

0.75.2

yapi

修复 沙箱 提权问题

OpenAPI-Specification

OAS 3.1.0 Released!

swagger-ui

Swagger UI v4.10.3 Released!

generator-jhipster

v7.8.1

Popular Libraries in Swagger

fastapi

by tiangolo doticonpythondoticon

star image 44054 doticonMIT

FastAPI framework, high performance, easy to learn, fast to code, ready for production

yapi

by YMFE doticonjavascriptdoticon

star image 23924 doticonApache-2.0

YApi 是一个可本地部署的、打通前后端及QA的、可视化的接口管理平台

OpenAPI-Specification

by OAI doticonjavascriptdoticon

star image 22782 doticonApache-2.0

The OpenAPI Specification Repository

swagger-ui

by swagger-api doticonjavascriptdoticon

star image 21807 doticonApache-2.0

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.

generator-jhipster

by jhipster doticonjavascriptdoticon

star image 19466 doticonApache-2.0

JHipster is a development platform to quickly generate, develop, & deploy modern web applications & microservice architectures.

redoc

by Redocly doticontypescriptdoticon

star image 17055 doticonMIT

📘 OpenAPI/Swagger-generated API Reference Documentation

eladmin

by elunez doticonjavadoticon

star image 16868 doticonApache-2.0

项目基于 Spring Boot 2.1.0 、 Jpa、 Spring Security、redis、Vue的前后端分离的后台管理系统,项目采用分模块开发方式, 权限控制采用 RBAC,支持数据字典与数据权限管理,支持一键生成前后端代码,支持动态路由

grpc-gateway

by grpc-ecosystem doticongodoticon

star image 13132 doticonBSD-3-Clause

gRPC to JSON proxy generator following the gRPC HTTP spec

gin-vue-admin

by flipped-aurora doticongodoticon

star image 12576 doticonApache-2.0

基于vite+vue3+gin搭建的开发基础平台(已完成setup语法糖版本),集成jwt鉴权,权限管理,动态路由,显隐可控组件,分页封装,多点登录拦截,资源权限,上传下载,代码生成器,表单生成器等开发必备功能,五分钟一套CURD前后端代码。

Trending New libraries in Swagger

go-admin

by go-admin-team doticongodoticon

star image 5884 doticonMIT

基于Gin + Vue + Element UI的前后端分离权限管理系统脚手架(包含了:多租户的支持,基础用户管理功能,jwt鉴权,代码生成器,RBAC资源控制,表单构建,定时任务等)3分钟构建自己的中后台项目;文档:https://doc.go-admin.dev Demo: https://www.go-admin.dev Antd beta版本:https://preview.go-admin.dev

django-ninja

by vitalik doticonpythondoticon

star image 2769 doticonMIT

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs

opyrator

by ml-tooling doticonpythondoticon

star image 2593 doticonMIT

🪄 Turns your machine learning code into microservices with web API, interactive GUI, and more.

restler-fuzzer

by microsoft doticonpythondoticon

star image 1570 doticonMIT

RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

best-of-web-python

by ml-tooling doticonpythondoticon

star image 1488 doticonCC-BY-SA-4.0

🏆 A ranked list of awesome python libraries for web development. Updated weekly.

JooLun-wx

by Joolun doticonjavadoticon

star image 1363 doticonMIT

JooLun微信商城,Java + SpringBoot + Maven + Swagger + Mybatis Plus + Redis + Vue + elementUI,微信公众号开发、小程序商城、微信支付、订单管理;商业版还有微服务、多租户Sass、Uniapp商城、小程序直播、多规格SKU、拼团、砍价、商户管理、 秒杀、优惠券、积分、多店铺、商城拖拽装修、服务商收款等功能

flask-restx

by python-restx doticonpythondoticon

star image 1171 doticonNOASSERTION

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask

drf-spectacular

by tfranzel doticonpythondoticon

star image 962 doticonBSD-3-Clause

Sane and flexible OpenAPI 3 schema generation for Django REST framework.

ego

by gotomicro doticongodoticon

star image 690 doticonMIT

A simple and component-based microservice kit for go.

Top Authors in Swagger

1

swagger-api

19 Libraries

star icon44532

2

Mermade

12 Libraries

star icon3420

3

Azure

11 Libraries

star icon5356

4

apiaryio

10 Libraries

star icon4084

5

stoplightio

9 Libraries

star icon4914

6

microsoft

9 Libraries

star icon5686

7

IBM

9 Libraries

star icon1612

8

NHSDigital

9 Libraries

star icon29

9

apigee-127

8 Libraries

star icon1169

10

cdimascio

8 Libraries

star icon1787

1

19 Libraries

star icon44532

2

12 Libraries

star icon3420

3

11 Libraries

star icon5356

4

10 Libraries

star icon4084

5

9 Libraries

star icon4914

6

9 Libraries

star icon5686

7

9 Libraries

star icon1612

8

9 Libraries

star icon29

9

8 Libraries

star icon1169

10

8 Libraries

star icon1787

Trending Kits in Swagger

No Trending Kits are available at this moment for Swagger

Trending Discussions on Swagger

400 response to CORS preflight

Asp.Net Core 6 Sort Swagger UI Tags Alphabetically

Springboot 2.6.0 / Spring fox 3 - Failed to start bean 'documentationPluginsBootstrapper'

Keycloak 17: Unsatisfied dependency for type org.keycloak.models.KeycloakSession and qualifiers [@Default]

Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException

How to use appsettings.json in Asp.net core 6 Program.cs file

How can I use DateOnly/TimeOnly query parameters in ASP.NET Core 6?

502 Error: Bad Gateway on Azure App Service with IronPDF

How to specify schema for nested json in flask_restx?

How to enable cors in ASP.NET Core 6.0 Web API project?

QUESTION

400 response to CORS preflight

Asked 2022-Apr-02 at 10:21

I have swagger (docker: swaggerapi/swagger-ui) running on swagger.mydomain.com with two definitions for api servers running on a.mydomain.com and b.mydomain.com

Both a and b are flask (python) servers. a.mydomain.com had CORS set up for a while now due to serving a webapp on a fourth subdomain. This works fine both on that subdomain, as well as in swagger. Now I did the same CORS setup for b.mydomain.com, however without success.

The setup on both servers looks like this:

1from flask import Flask
2from flask_cors import CORS
3
4app = Flask(__name__)
5CORS(app, origins=r"^.*(mydomain\.com)")
6

As I said, this works on a.mydomain.com, but not on b.mydomain.com.

Preflight looks identical, except the urls, the status code (200 and 400 respectively) as well as that the working request has an additional allow: POST, OPTIONS header. I don't see any difference in code to justify this additional header.

The failed preflight request takes 150ms which is double of the working request.

Executing a request via swagger provides a curl request. Executing this locally gives the expected output, so the request is generally correct.

I have no idea what else to try. As far as I can see, a and b.mydomain.com are set up exactly the same. What could be wrong here?

ANSWER

Answered 2021-Sep-17 at 23:52

A 400 is a pretty unusual response code for a preflight response. That suggests the endpoint might be configured to expect a certain request body/payload or headers in the request regardless of what the HTTP method is for the request. But since for the preflight OPTIONS request, the browser sends no request body and no additional header, the server code is not receiving what it expects.

For such cases, the fix is to ensure you have a specific, separate handler for OPTIONS requests configured for that route/endpoint.

Source https://stackoverflow.com/questions/69227515

QUESTION

Asp.Net Core 6 Sort Swagger UI Tags Alphabetically

Asked 2022-Mar-29 at 21:28

I'm using asp.net core 6 & Swashbuckle.AspNetCore

and I'm using SwaggerAnnotations in my actions

But my Tags Groups are not ordered

Here's my Swagger UI page

enter image description here


My Program.cs :

1builder.Services.AddSwaggerGen(c => {
2  c.SwaggerDoc("v1", new OpenApiInfo {
3    Title = "Api", Version = "v1"
4  });
5  c.EnableAnnotations();
6});
7
8 ....
9
10var app = builder.Build();
11
12app.UseSwagger();
13app.UseSwaggerUI(c => {
14  c.SwaggerEndpoint("/swagger/v1/swagger.json", "Shoppy.WebApi");
15  c.InjectStylesheet("/swagger-ui/css/custom.css");
16});
17
18

ANSWER

Answered 2022-Feb-07 at 08:13

I got the solution

I created this Custom DocumentFiler thats sorts the Tags

1builder.Services.AddSwaggerGen(c => {
2  c.SwaggerDoc("v1", new OpenApiInfo {
3    Title = "Api", Version = "v1"
4  });
5  c.EnableAnnotations();
6});
7
8 ....
9
10var app = builder.Build();
11
12app.UseSwagger();
13app.UseSwaggerUI(c => {
14  c.SwaggerEndpoint("/swagger/v1/swagger.json", "Shoppy.WebApi");
15  c.InjectStylesheet("/swagger-ui/css/custom.css");
16});
17
18public class OrderTagsDocumentFilter: IDocumentFilter {
19  public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) {
20    swaggerDoc.Tags = swaggerDoc.Tags.OrderBy(x => x.Name).ToList();
21  }
22}
23
24

and added it to Program.cs

1builder.Services.AddSwaggerGen(c => {
2  c.SwaggerDoc("v1", new OpenApiInfo {
3    Title = "Api", Version = "v1"
4  });
5  c.EnableAnnotations();
6});
7
8 ....
9
10var app = builder.Build();
11
12app.UseSwagger();
13app.UseSwaggerUI(c => {
14  c.SwaggerEndpoint("/swagger/v1/swagger.json", "Shoppy.WebApi");
15  c.InjectStylesheet("/swagger-ui/css/custom.css");
16});
17
18public class OrderTagsDocumentFilter: IDocumentFilter {
19  public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) {
20    swaggerDoc.Tags = swaggerDoc.Tags.OrderBy(x => x.Name).ToList();
21  }
22}
23
24
25services.AddSwaggerGen(c => {
26  c.SwaggerDoc("v1", new OpenApiInfo {
27    Title = "Shoppy.WebApi", Version = "v1"
28  });
29  c.EnableAnnotations();
30
31  c.DocumentFilter<OrderTagsDocumentFilter>();
32});
33
34

Source https://stackoverflow.com/questions/71010212

QUESTION

Springboot 2.6.0 / Spring fox 3 - Failed to start bean 'documentationPluginsBootstrapper'

Asked 2022-Mar-25 at 06:14

I'm trying to initiate a Springboot project using Open Jdk 15, Springboot 2.6.0, Springfox 3. We are working on a project that replaced Netty as the webserver and used Jetty instead because we do not need a non-blocking environment.

In the code we depend primarily on Reactor API (Flux, Mono), so we can not remove org.springframework.boot:spring-boot-starter-webflux dependencies.

I replicated the problem that we have in a new project.: https://github.com/jvacaq/spring-fox.

I figured out that these lines in our build.gradle file are the origin of the problem.

1compile("org.springframework.boot:spring-boot-starter-web") {
2   exclude module: "spring-boot-starter-tomcat"
3}
4compile("org.springframework.boot:spring-boot-starter-jetty")
5

Here is the build.gradle file:

1compile("org.springframework.boot:spring-boot-starter-web") {
2   exclude module: "spring-boot-starter-tomcat"
3}
4compile("org.springframework.boot:spring-boot-starter-jetty")
5plugins {
6    id 'org.springframework.boot' version '2.6.0'
7    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
8    id 'java'
9}
10
11group = 'com.example'
12version = '0.0.1-SNAPSHOT'
13sourceCompatibility = '11'
14
15repositories {
16    mavenCentral()
17}
18
19dependencies {
20    compile("org.springframework.boot:spring-boot-starter-web") {
21        exclude module: "spring-boot-starter-tomcat"
22    }
23    compile("org.springframework.boot:spring-boot-starter-jetty")
24    implementation 'org.springframework.boot:spring-boot-starter-webflux'
25    testImplementation 'org.springframework.boot:spring-boot-starter-test'
26    testImplementation 'io.projectreactor:reactor-test'
27    implementation "io.springfox:springfox-boot-starter:3.0.0"
28}
29
30test {
31    useJUnitPlatform()
32}
33
34

I issued the command gradle clean bootrun. The result is this error:

1compile("org.springframework.boot:spring-boot-starter-web") {
2   exclude module: "spring-boot-starter-tomcat"
3}
4compile("org.springframework.boot:spring-boot-starter-jetty")
5plugins {
6    id 'org.springframework.boot' version '2.6.0'
7    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
8    id 'java'
9}
10
11group = 'com.example'
12version = '0.0.1-SNAPSHOT'
13sourceCompatibility = '11'
14
15repositories {
16    mavenCentral()
17}
18
19dependencies {
20    compile("org.springframework.boot:spring-boot-starter-web") {
21        exclude module: "spring-boot-starter-tomcat"
22    }
23    compile("org.springframework.boot:spring-boot-starter-jetty")
24    implementation 'org.springframework.boot:spring-boot-starter-webflux'
25    testImplementation 'org.springframework.boot:spring-boot-starter-test'
26    testImplementation 'io.projectreactor:reactor-test'
27    implementation "io.springfox:springfox-boot-starter:3.0.0"
28}
29
30test {
31    useJUnitPlatform()
32}
33
34 gradle clean bootrun                                                                                                                                                                                                               
35
36> Task :bootRun FAILED
37
38  .   ____          _            __ _ _
39 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
40( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
41 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
42  '  |____| .__|_| |_|_| |_\__, | / / / /
43 =========|_|==============|___/=/_/_/_/
44 :: Spring Boot ::                (v2.6.0)
45
462021-11-19 09:41:06.665  INFO 16666 --- [           main] c.e.springfox.SpringFoxApplication       : Starting SpringFoxApplication using Java 15.0.2 on advance-Inspiron-5379 with PID 16666 (/home/advance/projects/spring-fox/build/classes/java/main started by advance in /home/advance/projects/spring-fox)
472021-11-19 09:41:06.666  INFO 16666 --- [           main] c.e.springfox.SpringFoxApplication       : No active profile set, falling back to default profiles: default
482021-11-19 09:41:07.294  INFO 16666 --- [           main] org.eclipse.jetty.util.log               : Logging initialized @1132ms to org.eclipse.jetty.util.log.Slf4jLog
492021-11-19 09:41:07.396  INFO 16666 --- [           main] o.s.b.w.e.j.JettyServletWebServerFactory : Server initialized with port: 8080
502021-11-19 09:41:07.398  INFO 16666 --- [           main] org.eclipse.jetty.server.Server          : jetty-9.4.44.v20210927; built: 2021-09-27T23:02:44.612Z; git: 8da83308eeca865e495e53ef315a249d63ba9332; jvm 15.0.2+7-27
512021-11-19 09:41:07.417  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Initializing Spring embedded WebApplicationContext
522021-11-19 09:41:07.417  INFO 16666 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 713 ms
532021-11-19 09:41:07.474  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : DefaultSessionIdManager workerName=node0
542021-11-19 09:41:07.474  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : No SessionScavenger set, using defaults
552021-11-19 09:41:07.475  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : node0 Scavenging every 660000ms
562021-11-19 09:41:07.480  INFO 16666 --- [           main] o.e.jetty.server.handler.ContextHandler  : Started o.s.b.w.e.j.JettyEmbeddedWebAppContext@6aa3bfc{application,/,[file:///tmp/jetty-docbase.8080.2024342829220941812/, jar:file:/home/advance/.gradle/caches/modules-2/files-2.1/io.springfox/springfox-swagger-ui/3.0.0/1e665fbe22148f7c36fa8a08e515a0047cd4390b/springfox-swagger-ui-3.0.0.jar!/META-INF/resources],AVAILABLE}
572021-11-19 09:41:07.480  INFO 16666 --- [           main] org.eclipse.jetty.server.Server          : Started @1318ms
582021-11-19 09:41:07.920  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Initializing Spring DispatcherServlet 'dispatcherServlet'
592021-11-19 09:41:07.920  INFO 16666 --- [           main] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
602021-11-19 09:41:07.921  INFO 16666 --- [           main] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
612021-11-19 09:41:07.931  INFO 16666 --- [           main] o.e.jetty.server.AbstractConnector       : Started ServerConnector@2643d762{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
622021-11-19 09:41:07.932  INFO 16666 --- [           main] o.s.b.web.embedded.jetty.JettyWebServer  : Jetty started on port(s) 8080 (http/1.1) with context path '/'
632021-11-19 09:41:07.934  WARN 16666 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
642021-11-19 09:41:07.949  INFO 16666 --- [           main] o.e.jetty.server.AbstractConnector       : Stopped ServerConnector@2643d762{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
652021-11-19 09:41:07.950  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : node0 Stopped scavenging
662021-11-19 09:41:07.951  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Destroying Spring FrameworkServlet 'dispatcherServlet'
672021-11-19 09:41:07.951  INFO 16666 --- [           main] o.e.jetty.server.handler.ContextHandler  : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext@6aa3bfc{application,/,[file:///tmp/jetty-docbase.8080.2024342829220941812/, jar:file:/home/advance/.gradle/caches/modules-2/files-2.1/io.springfox/springfox-swagger-ui/3.0.0/1e665fbe22148f7c36fa8a08e515a0047cd4390b/springfox-swagger-ui-3.0.0.jar!/META-INF/resources],STOPPED}
682021-11-19 09:41:07.958  INFO 16666 --- [           main] ConditionEvaluationReportLoggingListener : 
69
70Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
712021-11-19 09:41:07.970 ERROR 16666 --- [           main] o.s.boot.SpringApplication               : Application run failed
72
73org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
74        at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.13.jar:5.3.13]
75        at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.13.jar:5.3.13]
76        at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.13.jar:5.3.13]
77        at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
78        at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.13.jar:5.3.13]
79        at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.13.jar:5.3.13]
80        at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.13.jar:5.3.13]
81        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.13.jar:5.3.13]
82        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.0.jar:2.6.0]
83        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.0.jar:2.6.0]
84        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.0.jar:2.6.0]
85        at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.0.jar:2.6.0]
86        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.0.jar:2.6.0]
87        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.0.jar:2.6.0]
88        at com.example.springfox.SpringFoxApplication.main(SpringFoxApplication.java:10) ~[main/:na]
89Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
90        at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
91        at springfox.documentation.RequestHandler.sortedPaths(RequestHandler.java:113) ~[springfox-core-3.0.0.jar:3.0.0]
92        at springfox.documentation.spi.service.contexts.Orderings.lambda$byPatternsCondition$3(Orderings.java:89) ~[springfox-spi-3.0.0.jar:3.0.0]
93        at java.base/java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) ~[na:na]
94        at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:na]
95        at java.base/java.util.TimSort.sort(TimSort.java:220) ~[na:na]
96        at java.base/java.util.Arrays.sort(Arrays.java:1306) ~[na:na]
97        at java.base/java.util.ArrayList.sort(ArrayList.java:1721) ~[na:na]
98        at java.base/java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:392) ~[na:na]
99        at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
100        at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
101        at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
102        at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
103        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485) ~[na:na]
104        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
105        at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
106        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
107        at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
108        at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:81) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
109        at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) ~[na:na]
110        at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
111        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
112        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
113        at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
114        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
115        at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
116        at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.withDefaults(AbstractDocumentationPluginsBootstrapper.java:107) ~[springfox-spring-web-3.0.0.jar:3.0.0]
117        at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.buildContext(AbstractDocumentationPluginsBootstrapper.java:91) ~[springfox-spring-web-3.0.0.jar:3.0.0]
118        at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.bootstrapDocumentationPlugins(AbstractDocumentationPluginsBootstrapper.java:82) ~[springfox-spring-web-3.0.0.jar:3.0.0]
119        at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:100) ~[springfox-spring-web-3.0.0.jar:3.0.0]
120        at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.13.jar:5.3.13]
121        ... 14 common frames omitted
122
123
124FAILURE: Build failed with an exception.
125
126* What went wrong:
127Execution failed for task ':bootRun'.
128> Process 'command '/home/advance/.sdkman/candidates/java/15.0.2-open/bin/java'' finished with non-zero exit value 1
129
130* Try:
131Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
132
133* Get more help at https://help.gradle.org
134
135Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
136Use '--warning-mode all' to show the individual deprecation warnings.
137See https://docs.gradle.org/6.9.1/userguide/command_line_interface.html#sec:command_line_warnings
138
139BUILD FAILED in 2s
1405 actionable tasks: 5 executed
141

Does anyone have an idea how to solve it?

ANSWER

Answered 2022-Feb-08 at 12:36

This problem's caused by a bug in Springfox. It's making an assumption about how Spring MVC is set up that doesn't always hold true. Specifically, it's assuming that MVC's path matching will use the Ant-based path matcher and not the PathPattern-based matcher. PathPattern-based matching has been an option for some time now and is the default as of Spring Boot 2.6.

As described in Spring Boot 2.6's release notes, you can restore the configuration that Springfox assumes will be used by setting spring.mvc.pathmatch.matching-strategy to ant-path-matcher in your application.properties file. Note that this will only work if you are not using Spring Boot's Actuator. The Actuator always uses PathPattern-based parsing, irrespective of the configured matching-strategy. A change to Springfox will be required if you want to use it with the Actuator in Spring Boot 2.6 and later.

Source https://stackoverflow.com/questions/70036953

QUESTION

Keycloak 17: Unsatisfied dependency for type org.keycloak.models.KeycloakSession and qualifiers [@Default]

Asked 2022-Mar-23 at 09:03

We are using keycloak as IDP and have some custom plugins/Spi, we are in process of updating our keycloak instance to version 17 Quarkas distribution and the SPIs began to break (error below) during keycloak build process. I've made sure that there are no keycloak libraries packed as part of jar.

The SPI looks like below and have corresponding entries in Manifest file under Manifest/services/org.keycloak.services.resource.RealmResourceProviderFactory

Custom SPI/plugin

1public class SwaggerJsonRetrieverFactory implements RealmResourceProviderFactory {
2    @Override
3    public RealmResourceProvider create(KeycloakSession session) {
4        return new SwaggerJsonRetriever(session);
5    }
6
7
8    @Override
9    public void init(Config.Scope config) {
10
11    }
12
13
14    @Override
15    public void postInit(KeycloakSessionFactory factory) {
16
17    }
18
19
20    @Override
21    public void close() {
22
23    }
24
25    @Override
26    public String getId() {
27        return "swagger.json";
28    }
29}
30
31

My pom.xml looks like below

1public class SwaggerJsonRetrieverFactory implements RealmResourceProviderFactory {
2    @Override
3    public RealmResourceProvider create(KeycloakSession session) {
4        return new SwaggerJsonRetriever(session);
5    }
6
7
8    @Override
9    public void init(Config.Scope config) {
10
11    }
12
13
14    @Override
15    public void postInit(KeycloakSessionFactory factory) {
16
17    }
18
19
20    @Override
21    public void close() {
22
23    }
24
25    @Override
26    public String getId() {
27        return "swagger.json";
28    }
29}
30
31<dependencies>
32        <dependency>
33            <groupId>org.keycloak</groupId>
34            <artifactId>keycloak-core</artifactId>
35            <scope>provided</scope>
36            <version>${keycloak.version}</version>
37        </dependency>
38        <dependency>
39            <groupId>org.keycloak</groupId>
40            <artifactId>keycloak-server-spi</artifactId>
41            <version>${keycloak.version}</version>
42        </dependency>
43        <dependency>
44            <groupId>org.keycloak</groupId>
45            <artifactId>keycloak-services</artifactId>
46            <scope>provided</scope>
47            <version>${keycloak.version}</version>
48        </dependency>
49        <dependency>
50            <groupId>org.keycloak</groupId>
51            <artifactId>keycloak-server-spi-private</artifactId>
52            <scope>provided</scope>
53            <version>${keycloak.version}</version>
54        </dependency>
55        <dependency>
56            <groupId>io.swagger</groupId>
57            <artifactId>swagger-parser</artifactId>
58            <version>1.0.22</version>
59        </dependency>
60        <dependency>
61            <groupId>ch.qos.logback</groupId>
62            <artifactId>logback-classic</artifactId>
63            <version>${logback.version}</version>
64        </dependency>
65        <dependency>
66            <groupId>ch.qos.logback</groupId>
67            <artifactId>logback-core</artifactId>
68            <version>${logback.version}</version>
69        </dependency>
70        <dependency>
71            <groupId>com.fasterxml.jackson.dataformat</groupId>
72            <artifactId>jackson-dataformat-yaml</artifactId>
73            <version>${jackson-dataformat-yaml.version}</version>
74        </dependency>
75        <dependency>
76            <groupId>org.jboss.spec.javax.ws.rs</groupId>
77            <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
78            <version>2.0.1.Final</version>
79        </dependency>
80
81    </dependencies>
82

The error which I'm getting

1public class SwaggerJsonRetrieverFactory implements RealmResourceProviderFactory {
2    @Override
3    public RealmResourceProvider create(KeycloakSession session) {
4        return new SwaggerJsonRetriever(session);
5    }
6
7
8    @Override
9    public void init(Config.Scope config) {
10
11    }
12
13
14    @Override
15    public void postInit(KeycloakSessionFactory factory) {
16
17    }
18
19
20    @Override
21    public void close() {
22
23    }
24
25    @Override
26    public String getId() {
27        return "swagger.json";
28    }
29}
30
31<dependencies>
32        <dependency>
33            <groupId>org.keycloak</groupId>
34            <artifactId>keycloak-core</artifactId>
35            <scope>provided</scope>
36            <version>${keycloak.version}</version>
37        </dependency>
38        <dependency>
39            <groupId>org.keycloak</groupId>
40            <artifactId>keycloak-server-spi</artifactId>
41            <version>${keycloak.version}</version>
42        </dependency>
43        <dependency>
44            <groupId>org.keycloak</groupId>
45            <artifactId>keycloak-services</artifactId>
46            <scope>provided</scope>
47            <version>${keycloak.version}</version>
48        </dependency>
49        <dependency>
50            <groupId>org.keycloak</groupId>
51            <artifactId>keycloak-server-spi-private</artifactId>
52            <scope>provided</scope>
53            <version>${keycloak.version}</version>
54        </dependency>
55        <dependency>
56            <groupId>io.swagger</groupId>
57            <artifactId>swagger-parser</artifactId>
58            <version>1.0.22</version>
59        </dependency>
60        <dependency>
61            <groupId>ch.qos.logback</groupId>
62            <artifactId>logback-classic</artifactId>
63            <version>${logback.version}</version>
64        </dependency>
65        <dependency>
66            <groupId>ch.qos.logback</groupId>
67            <artifactId>logback-core</artifactId>
68            <version>${logback.version}</version>
69        </dependency>
70        <dependency>
71            <groupId>com.fasterxml.jackson.dataformat</groupId>
72            <artifactId>jackson-dataformat-yaml</artifactId>
73            <version>${jackson-dataformat-yaml.version}</version>
74        </dependency>
75        <dependency>
76            <groupId>org.jboss.spec.javax.ws.rs</groupId>
77            <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
78            <version>2.0.1.Final</version>
79        </dependency>
80
81    </dependencies>
82 io.quarkus.builder.BuildException: Build failure: Build failed due to errors
83    [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 2 deployment problems: 
84[1] Unsatisfied dependency for type org.keycloak.models.KeycloakSession and qualifiers [@Default]
85    - java member: com.abc.swagger.SwaggerJsonRetriever().session
86    - declared on CLASS bean [types=[com.abc.swagger.SwaggerJsonRetriever, java.lang.Object], qualifiers=[@Default, @Any], target=com.abc.swagger.SwaggerJsonRetriever]
87[2] Unsatisfied dependency for type org.keycloak.models.KeycloakSession and qualifiers [@Default]
88

Is there any configuration which I'm missing, any help will be appreciated.

ANSWER

Answered 2022-Mar-23 at 09:03

Remove @Path annotation from class.

Source https://stackoverflow.com/questions/71427463

QUESTION

Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException

Asked 2022-Mar-03 at 15:46

I'm using Asp.Net Core Web Api 6

I'm facing an error when migrating my DbContext and when updating the database

The Error

1[17:07:29 INF] Application Is Starting
2[17:07:29 FTL] Application terimnated unexpectedly
3Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
4   at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
5   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
6   at Microsoft.Extensions.Hosting.HostBuilder.Build()
7   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
8   at Program.<Main>$(String[] args) in C:\...\Program.cs:line 44
9
10

But it does not affect the Migration process and Update-Database

Therefore, My question is,

  • How to fix it
  • Is this going to affect the project later?

Program.cs

1[17:07:29 INF] Application Is Starting
2[17:07:29 FTL] Application terimnated unexpectedly
3Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
4   at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
5   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
6   at Microsoft.Extensions.Hosting.HostBuilder.Build()
7   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
8   at Program.<Main>$(String[] args) in C:\...\Program.cs:line 44
9
10Log.Information("Application Is Starting");
11
12    var builder = WebApplication.CreateBuilder(args);
13
14    // Full setup of serilog. We read log settings from appsettings.json
15    builder.Host.UseSerilog((context, services, configuration) => configuration
16        .ReadFrom.Configuration(context.Configuration)
17        .ReadFrom.Services(services)
18        .Enrich.FromLogContext());
19
20
21    // Add services to the container.
22    builder.Services.AddDbContext<LocalDbContext>(options =>
23        options.UseSqlServer(builder.Configuration.GetConnectionString("localConnection"))
24    );
25
26    builder.Services.AddControllers();
27    builder.Services.AddCors(options =>
28    {
29        options.AddPolicy("AllowAll", builder =>
30            builder
31                .AllowAnyOrigin()
32                .AllowAnyMethod()
33                .AllowAnyHeader()
34            );
35    });
36    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
37    builder.Services.AddEndpointsApiExplorer();
38    builder.Services.AddSwaggerGen();
39
40    var app = builder.Build();
41
42    app.UseSerilogRequestLogging(configure =>
43    {
44        configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms";
45    });
46
47    // Configure the HTTP request pipeline.
48    if (app.Environment.IsDevelopment())
49    {
50        app.UseSwagger();
51        app.UseSwaggerUI();
52    }
53
54    app.UseCors("AllowAll");
55
56    app.UseHttpsRedirection();
57
58    app.UseAuthorization();
59
60    app.MapControllers();
61
62    app.Run();
63

ANSWER

Answered 2022-Mar-03 at 15:46

Add try/catch similar to the above around IHostBulder.Build() in any .NET/EF Core 6.0 RC2 project, and attempt to add a migration can reproduce the issue.

We can fix the issue with the following :

1[17:07:29 INF] Application Is Starting
2[17:07:29 FTL] Application terimnated unexpectedly
3Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
4   at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
5   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
6   at Microsoft.Extensions.Hosting.HostBuilder.Build()
7   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
8   at Program.<Main>$(String[] args) in C:\...\Program.cs:line 44
9
10Log.Information("Application Is Starting");
11
12    var builder = WebApplication.CreateBuilder(args);
13
14    // Full setup of serilog. We read log settings from appsettings.json
15    builder.Host.UseSerilog((context, services, configuration) => configuration
16        .ReadFrom.Configuration(context.Configuration)
17        .ReadFrom.Services(services)
18        .Enrich.FromLogContext());
19
20
21    // Add services to the container.
22    builder.Services.AddDbContext<LocalDbContext>(options =>
23        options.UseSqlServer(builder.Configuration.GetConnectionString("localConnection"))
24    );
25
26    builder.Services.AddControllers();
27    builder.Services.AddCors(options =>
28    {
29        options.AddPolicy("AllowAll", builder =>
30            builder
31                .AllowAnyOrigin()
32                .AllowAnyMethod()
33                .AllowAnyHeader()
34            );
35    });
36    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
37    builder.Services.AddEndpointsApiExplorer();
38    builder.Services.AddSwaggerGen();
39
40    var app = builder.Build();
41
42    app.UseSerilogRequestLogging(configure =>
43    {
44        configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms";
45    });
46
47    // Configure the HTTP request pipeline.
48    if (app.Environment.IsDevelopment())
49    {
50        app.UseSwagger();
51        app.UseSwaggerUI();
52    }
53
54    app.UseCors("AllowAll");
55
56    app.UseHttpsRedirection();
57
58    app.UseAuthorization();
59
60    app.MapControllers();
61
62    app.Run();
63catch (Exception ex)
64{
65   string type = ex.GetType().Name;
66   if (type.Equals("StopTheHostException", StringComparison.Ordinal))
67   {
68      throw;
69   }
70
71   _logger.Fatal(ex, "Unhandled exception");
72   return 1;
73}
74

For more details on this issue, you can refer to this article.

StopTheHostException should be made public to be dealt with gracefully #60600

Source https://stackoverflow.com/questions/70247187

QUESTION

How to use appsettings.json in Asp.net core 6 Program.cs file

Asked 2022-Feb-25 at 21:39

I'm trying to access appsettings.json in my Asp.net core v6 application Program.cs file, but in this version of .Net the Startup class and Program class are merged together and the using and another statements are simplified and removed from Program.cs. In this situation, How to access IConfiguration or how to use dependency injection for example ?

Edited : Here is my default Program.cs that Asp.net 6 created for me

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =>
5{
6    options.Configuration = "localhost:6379";
7});
8
9builder.Services.AddSwaggerGen(c =>
10{
11    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24

For example , I want to use appsettings.json instead of hard typed connectionstring in this line :

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =>
5{
6    options.Configuration = "localhost:6379";
7});
8
9builder.Services.AddSwaggerGen(c =>
10{
11    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = "localhost:6379";
25

ANSWER

Answered 2021-Sep-30 at 11:13

Assuming an appsettings.json

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =>
5{
6    options.Configuration = "localhost:6379";
7});
8
9builder.Services.AddSwaggerGen(c =>
10{
11    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = "localhost:6379";
25{
26    "RedisCacheOptions" : {
27        "Configuration": "localhost:6379"
28    }
29}
30

There is nothing stopping you from building a configuration object to extract the desired settings.

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =>
5{
6    options.Configuration = "localhost:6379";
7});
8
9builder.Services.AddSwaggerGen(c =>
10{
11    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = "localhost:6379";
25{
26    "RedisCacheOptions" : {
27        "Configuration": "localhost:6379"
28    }
29}
30IConfiguration configuration = new ConfigurationBuilder()
31                            .AddJsonFile("appsettings.json")
32                            .Build();
33
34var builder = WebApplication.CreateBuilder(args);
35// Add services to the container.
36builder.Services.AddControllers();
37builder.Services.AddStackExchangeRedisCache(options => {
38    options.Configuration = configuration["RedisCacheOptions:Configuration"];
39});
40
41//...
42

Source https://stackoverflow.com/questions/69390676

QUESTION

How can I use DateOnly/TimeOnly query parameters in ASP.NET Core 6?

Asked 2022-Feb-15 at 00:01

As of .NET 6 in ASP.NET API, if you want to get DateOnly (or TimeOnly) as query parameter, you need to separately specify all it's fields instead of just providing a string ("2021-09-14", or "10:54:53" for TimeOnly) like you can for DateTime.

I was able to fix that if they are part of the body by adding adding custom JSON converter (AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(...))), but it doesn't work for query parameters.

I know that could be fixed with model binder, but I don't want to create a model binder for every model that contains DateOnly/TimeOnly. Is there a way to fix this application wide?

Demo:

Lets assume you have a folowwing action:

[HttpGet] public void Foo([FromQuery] DateOnly date, [FromQuery] TimeOnly time, [FromQuery] DateTime dateTime)

Here's how it would be represented in Swagger:

enter image description here

I want it represented as three string fields: one for DateOnly, one for TimeOnly and one for DateTime (this one is already present).

PS: It's not a Swagger problem, it's ASP.NET one. If I try to pass ?date=2021-09-14 manually, ASP.NET wouldn't understand it.

ANSWER

Answered 2021-Sep-16 at 10:02

I also met your issue in my side and it seems the constructor itself doesn't support parameter-less mode. As the code below :

1public DateOnly(int year, int month, int day)
2        {
3            throw null;
4        }
5
6        [NullableContext(1)]
7        public DateOnly(int year, int month, int day, Calendar calendar)
8        {
9            throw null;
10        }
11

While the DateTime supports:

1public DateOnly(int year, int month, int day)
2        {
3            throw null;
4        }
5
6        [NullableContext(1)]
7        public DateOnly(int year, int month, int day, Calendar calendar)
8        {
9            throw null;
10        }
11public DateTime Date
12    {
13        get
14        {
15            throw null;
16        }
17    }
18

Therefore, I'm afraid before some updating on DateOnly and TimeOnly, we all need to use string instead and divide the string into year, month and day and then new DateOnly(int year, int month, int day).

Source https://stackoverflow.com/questions/69187622

QUESTION

502 Error: Bad Gateway on Azure App Service with IronPDF

Asked 2022-Jan-10 at 08:54

I am attempting to get IronPDF working on my deployment of an ASP.NET Core 3.1 App Service. I am not using Azure Functions for any of this, just a regular endpoints on an Azure App Service -which, when a user calls it, the service generates and returns a generated PDF document.

When running the endpoint on localhost, it works perfectly- generating the report from the HTML passed into the method. However, once I deploy it to my Azure Web App Service, I am getting a 502 - Bad Gateway error, as attached (displayed in Swagger for neatness sake).

enter image description here

Controller:

1[HttpPost]
2[Route("[action]")]
3[ProducesResponseType(StatusCodes.Status200OK)]
4public async Task<IActionResult> AgencyDownload([FromBody] AgencyReportSubmissionDto filters)
5{
6  var user = await _userService.GetUserByIdAsync(HttpContext.User.GetUserId());
7
8  // Generate the PDF
9  var content = await _agencyReport.Generate(user, null, filters.FilterDate, filters.Content, filters.Type);
10
11  // Return the PDF to the browser
12  return new FileContentResult(content.BinaryData, "application/pdf") { FileDownloadName = "report.pdf" };
13}
14

Service:

1[HttpPost]
2[Route("[action]")]
3[ProducesResponseType(StatusCodes.Status200OK)]
4public async Task<IActionResult> AgencyDownload([FromBody] AgencyReportSubmissionDto filters)
5{
6  var user = await _userService.GetUserByIdAsync(HttpContext.User.GetUserId());
7
8  // Generate the PDF
9  var content = await _agencyReport.Generate(user, null, filters.FilterDate, filters.Content, filters.Type);
10
11  // Return the PDF to the browser
12  return new FileContentResult(content.BinaryData, "application/pdf") { FileDownloadName = "report.pdf" };
13}
14public async Task<PdfDocument> Generate(User user, byte[] letterhead, DateTimeOffset filterDate, string html, AgencyReportTypes reportType)
15{
16   var corporateIdentity = new CorporateIdentity()
17   {
18        PrimaryColor = "#000000",
19        PrimaryTextColor = "#ffffff",
20        SecondaryColor = "#ffffff"
21   };
22
23    // Inserts the HTML content (from form) into the HTML template
24    var htmlContent = Template(corporateIdentity.PrimaryColor, corporateIdentity.PrimaryTextColor).Replace("{{HtmlContent}}", html);
25        
26    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("South Africa Standard Time");
27    var convertedDate = TimeZoneInfo.ConvertTimeFromUtc(filterDate.UtcDateTime, tz);
28    var Renderer = new ChromePdfRenderer();
29
30    Renderer.RenderingOptions.Title = "Agency Report - for " + convertedDate.ToString("d MMMM yyyy");
31    Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
32
33    var doc = await Renderer.RenderHtmlAsPdfAsync(htmlContent);
34    return doc;
35}
36

Solution:

I noticed that if I performed a manual deployment to that app service, it was working, but when I was deploying from my pipeline- I had the error above.

So I went snooping around my pipelines and upon changing it to this, it worked.

1[HttpPost]
2[Route("[action]")]
3[ProducesResponseType(StatusCodes.Status200OK)]
4public async Task<IActionResult> AgencyDownload([FromBody] AgencyReportSubmissionDto filters)
5{
6  var user = await _userService.GetUserByIdAsync(HttpContext.User.GetUserId());
7
8  // Generate the PDF
9  var content = await _agencyReport.Generate(user, null, filters.FilterDate, filters.Content, filters.Type);
10
11  // Return the PDF to the browser
12  return new FileContentResult(content.BinaryData, "application/pdf") { FileDownloadName = "report.pdf" };
13}
14public async Task<PdfDocument> Generate(User user, byte[] letterhead, DateTimeOffset filterDate, string html, AgencyReportTypes reportType)
15{
16   var corporateIdentity = new CorporateIdentity()
17   {
18        PrimaryColor = "#000000",
19        PrimaryTextColor = "#ffffff",
20        SecondaryColor = "#ffffff"
21   };
22
23    // Inserts the HTML content (from form) into the HTML template
24    var htmlContent = Template(corporateIdentity.PrimaryColor, corporateIdentity.PrimaryTextColor).Replace("{{HtmlContent}}", html);
25        
26    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("South Africa Standard Time");
27    var convertedDate = TimeZoneInfo.ConvertTimeFromUtc(filterDate.UtcDateTime, tz);
28    var Renderer = new ChromePdfRenderer();
29
30    Renderer.RenderingOptions.Title = "Agency Report - for " + convertedDate.ToString("d MMMM yyyy");
31    Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
32
33    var doc = await Renderer.RenderHtmlAsPdfAsync(htmlContent);
34    return doc;
35}
36            - task: AzureRmWebAppDeployment@4
37              displayName: Deploy API Artifact
38              inputs:
39                ConnectionType: 'AzureRM'
40                AzureSubscription: 'My-Azure-Subscription'
41                enableCustomDeployment: true
42                DeploymentType: 'zipDeploy'
43                deployToSlotOrASE: true
44                SlotName: 'development'
45                AppType: 'webApp'
46                WebAppName: 'my-api'
47                Package: '$(Pipeline.Workspace)/**/API.zip'
48                ResourceGroupName: 'MyResource'
49

the 'DeploymentType: 'zipDeploy'" was key.

Thanks to Alex Hanneman for pointing me in the right direction.

ANSWER

Answered 2021-Dec-14 at 02:19

App Service runs your apps in a sandbox and most PDF libraries will fail. Looking at the IronPDF documentation, they say that you can run it in a VM or a container. Since you already are using App Service, simply package your app in a container, publish it to a container registry and configure App Service to run it.

Source https://stackoverflow.com/questions/70341723

QUESTION

How to specify schema for nested json in flask_restx?

Asked 2022-Jan-09 at 20:53

Im using flask_restx for swagger API's. The versions are as follows:

1python - 3.8.0
2flask  - 2.0.2
3flask_restx - 0.5.1
4

The following is the nested json I need to specify the schema for:

1python - 3.8.0
2flask  - 2.0.2
3flask_restx - 0.5.1
4dr_status_fields = app_api.model('DR Status',{
5    fields.String: {
6        "elasticsearch": {
7            "backup_status": fields.String,
8            "backup_folder": fields.String,
9        },
10        "mongodb": {
11            "backup_status": fields.String,
12            "backup_folder": fields.String,
13        },
14        "postgresdb": {
15            "backup_status": fields.String,
16            "backup_folder": fields.String,
17        },
18        "overall_backup_status": fields.String
19    }
20})
21

But with this when I load the swagger URL in browser , i get error in the command line:

1python - 3.8.0
2flask  - 2.0.2
3flask_restx - 0.5.1
4dr_status_fields = app_api.model('DR Status',{
5    fields.String: {
6        "elasticsearch": {
7            "backup_status": fields.String,
8            "backup_folder": fields.String,
9        },
10        "mongodb": {
11            "backup_status": fields.String,
12            "backup_folder": fields.String,
13        },
14        "postgresdb": {
15            "backup_status": fields.String,
16            "backup_folder": fields.String,
17        },
18        "overall_backup_status": fields.String
19    }
20})
21Unable to render schema
22Traceback (most recent call last):
23  File "/usr/local/lib/python3.8/site-packages/flask_restx/api.py", line 571, in __schema__
24    self._schema = Swagger(self).as_dict()
25  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 268, in as_dict
26    "definitions": self.serialize_definitions() or None,
27  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 623, in serialize_definitions
28    return dict(
29  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 624, in <genexpr>
30    (name, model.__schema__)
31  File "/usr/local/lib/python3.8/site-packages/flask_restx/model.py", line 76, in __schema__
32    schema = self._schema
33  File "/usr/local/lib/python3.8/site-packages/flask_restx/model.py", line 159, in _schema
34    properties[name] = field.__schema__
35AttributeError: 'dict' object has no attribute '__schema__'
36
37

I have tried checking the documentaion of flask_restx for any sample example usage. But could not find any. Please help regarding the same

Update

As per r-m-n answer i have tried to apply the same. But here the problem is there is a key i.e in Line No.2 of the above defined scheme -> fields.String: { . I think this is causing the issue. I have tried to use it as follows:

1python - 3.8.0
2flask  - 2.0.2
3flask_restx - 0.5.1
4dr_status_fields = app_api.model('DR Status',{
5    fields.String: {
6        "elasticsearch": {
7            "backup_status": fields.String,
8            "backup_folder": fields.String,
9        },
10        "mongodb": {
11            "backup_status": fields.String,
12            "backup_folder": fields.String,
13        },
14        "postgresdb": {
15            "backup_status": fields.String,
16            "backup_folder": fields.String,
17        },
18        "overall_backup_status": fields.String
19    }
20})
21Unable to render schema
22Traceback (most recent call last):
23  File "/usr/local/lib/python3.8/site-packages/flask_restx/api.py", line 571, in __schema__
24    self._schema = Swagger(self).as_dict()
25  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 268, in as_dict
26    "definitions": self.serialize_definitions() or None,
27  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 623, in serialize_definitions
28    return dict(
29  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 624, in <genexpr>
30    (name, model.__schema__)
31  File "/usr/local/lib/python3.8/site-packages/flask_restx/model.py", line 76, in __schema__
32    schema = self._schema
33  File "/usr/local/lib/python3.8/site-packages/flask_restx/model.py", line 159, in _schema
34    properties[name] = field.__schema__
35AttributeError: 'dict' object has no attribute '__schema__'
36
37dr_status_fields = app_api.model('Backup and restore related fields', {
38            "backup_status": fields.String,
39            "backup_folder": fields.String,
40})
41
42dr_db_fields = app_api.model('DR Status', {
43    "elasticsearch": fields.Nested(dr_status_fields),
44    "mongodb": fields.Nested(dr_status_fields),
45    "postgresdb": fields.Nested(dr_status_fields),
46    "overall_backup_status": fields.String
47})
48
49dr_timestamp_field = app_api.model('Timestamp', {
50    fields.String: fields.Nested(dr_db_fields)
51})
52
53

Here the dr_timestamp_field has resulted in the same issue.

ANSWER

Answered 2022-Jan-09 at 15:27
1python - 3.8.0
2flask  - 2.0.2
3flask_restx - 0.5.1
4dr_status_fields = app_api.model('DR Status',{
5    fields.String: {
6        "elasticsearch": {
7            "backup_status": fields.String,
8            "backup_folder": fields.String,
9        },
10        "mongodb": {
11            "backup_status": fields.String,
12            "backup_folder": fields.String,
13        },
14        "postgresdb": {
15            "backup_status": fields.String,
16            "backup_folder": fields.String,
17        },
18        "overall_backup_status": fields.String
19    }
20})
21Unable to render schema
22Traceback (most recent call last):
23  File "/usr/local/lib/python3.8/site-packages/flask_restx/api.py", line 571, in __schema__
24    self._schema = Swagger(self).as_dict()
25  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 268, in as_dict
26    "definitions": self.serialize_definitions() or None,
27  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 623, in serialize_definitions
28    return dict(
29  File "/usr/local/lib/python3.8/site-packages/flask_restx/swagger.py", line 624, in <genexpr>
30    (name, model.__schema__)
31  File "/usr/local/lib/python3.8/site-packages/flask_restx/model.py", line 76, in __schema__
32    schema = self._schema
33  File "/usr/local/lib/python3.8/site-packages/flask_restx/model.py", line 159, in _schema
34    properties[name] = field.__schema__
35AttributeError: 'dict' object has no attribute '__schema__'
36
37dr_status_fields = app_api.model('Backup and restore related fields', {
38            "backup_status": fields.String,
39            "backup_folder": fields.String,
40})
41
42dr_db_fields = app_api.model('DR Status', {
43    "elasticsearch": fields.Nested(dr_status_fields),
44    "mongodb": fields.Nested(dr_status_fields),
45    "postgresdb": fields.Nested(dr_status_fields),
46    "overall_backup_status": fields.String
47})
48
49dr_timestamp_field = app_api.model('Timestamp', {
50    fields.String: fields.Nested(dr_db_fields)
51})
52
53backup_fields = api.model('Backup fields', {
54    "backup_status": fields.String,
55    "backup_folder": fields.String
56})
57
58dr_status_fields = api.model('DR Status', {
59    "elasticsearch": fields.Nested(backup_fields),
60    "mongodb": fields.Nested(backup_fields),
61    "postgresdb": fields.Nested(backup_fields),
62    "overall_backup_status": fields.String
63})
64

Source https://stackoverflow.com/questions/70594476

QUESTION

How to enable cors in ASP.NET Core 6.0 Web API project?

Asked 2021-Dec-28 at 21:07

Configured CORS in my ASP.NET Core 6.0 Web API project. But the preflight request receives a http 405 error.

In other words HTTP OPTION is not allowed. Looks like cors is not enabled.

I've seen examples with config.EnableCors(); but there is no App_Start/WebApiConfig.cs in this project template.

What am I missing here?

Program.cs

1var builder = WebApplication.CreateBuilder(args);
2
3// Add services to the container.
4
5builder.Services.AddControllers();
6
7// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
8builder.Services.AddEndpointsApiExplorer();
9builder.Services.AddSwaggerGen();
10
11var devCorsPolicy = "devCorsPolicy";
12builder.Services.AddCors(options =>
13{
14    options.AddPolicy(devCorsPolicy, builder => {
15        //builder.WithOrigins("http://localhost:800").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
16        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
17        //builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
18        //builder.SetIsOriginAllowed(origin => true);
19    });
20});
21
22
23var app = builder.Build();
24
25if (app.Environment.IsDevelopment())
26{
27    app.UseSwagger();
28    app.UseSwaggerUI();
29    app.UseCors(devCorsPolicy);
30}
31else 
32{
33    app.UseHttpsRedirection();
34    app.UseAuthorization();
35    //app.UseCors(prodCorsPolicy);
36}
37
38app.MapControllers();
39
40app.Run();
41

ANSWER

Answered 2021-Dec-28 at 20:05

Add service builder.Services.AddCors and app add app.UseCors("corsapp");

replace builder.WithOrigins("*") with builder.WithOrigins("http://localhost:800", "https://misite.com");

check documentation

1var builder = WebApplication.CreateBuilder(args);
2
3// Add services to the container.
4
5builder.Services.AddControllers();
6
7// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
8builder.Services.AddEndpointsApiExplorer();
9builder.Services.AddSwaggerGen();
10
11var devCorsPolicy = "devCorsPolicy";
12builder.Services.AddCors(options =>
13{
14    options.AddPolicy(devCorsPolicy, builder => {
15        //builder.WithOrigins("http://localhost:800").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
16        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
17        //builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
18        //builder.SetIsOriginAllowed(origin => true);
19    });
20});
21
22
23var app = builder.Build();
24
25if (app.Environment.IsDevelopment())
26{
27    app.UseSwagger();
28    app.UseSwaggerUI();
29    app.UseCors(devCorsPolicy);
30}
31else 
32{
33    app.UseHttpsRedirection();
34    app.UseAuthorization();
35    //app.UseCors(prodCorsPolicy);
36}
37
38app.MapControllers();
39
40app.Run();
41     var builder = WebApplication.CreateBuilder(args);
42
43    
44    // Add services to the container.
45    
46    builder.Services.AddControllers();
47    
48    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
49    builder.Services.AddEndpointsApiExplorer();
50    builder.Services.AddSwaggerGen();
51    //services cors
52    builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
53    {
54        builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
55    }));
56    
57    var app = builder.Build();
58    
59    if (app.Environment.IsDevelopment())
60    {
61        app.UseSwagger();
62        app.UseSwaggerUI();
63        
64    }
65       //app cors
66        app.UseCors("corsapp");
67        app.UseHttpsRedirection();
68        app.UseAuthorization();
69        //app.UseCors(prodCorsPolicy);
70    
71    
72    
73    app.MapControllers();
74    
75    app.Run();
76

Source https://stackoverflow.com/questions/70511588

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Swagger

Tutorials and Learning Resources are not available at this moment for Swagger

Share this Page

share link

Get latest updates on Swagger