Facing issue with configure method in .Net core application - swagger

I have developed .Net core API project and deployed on the server.
I added it as site on IIS(remote windows server)and tried to browse the application.
The application is not working properly facing issue at Configure method
Here is my configure method in >net core
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var appName = "";
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api V1");
});
}
Please let me know how can to add swagger endpoint.

I guess you directly publish your web application to a nested site in the default website on IIS.
So the "/swagger/v1/swagger.json" root path will become localhost/swagger/v1/swagger.json not localhost/yourwebsitename/swagger/v1/swagger.json.
To solve this issue, I suggest you could try to modify the SwaggerEndpoint path as this `c.SwaggerEndpoint("../swagger/v1/swagger.json", "Api V1");.
More details, you could refer to below startup.cs
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v1/swagger.json", "Api V1");
});
`

Related

JWT authentication issue with web api plugin in nopCommerce 4.30

I implement JWT authentication for authorization using access token or bearer token in web api plugin with nopCommerce version 4.30. It is working fine with default source of nopCommerce 4.30. But when i used my API plugin with any Seven spikes plugins (SevenSpikes.Nop.Plugins.AjaxCart, SevenSpikes.Nop.Plugins.QuickView, etc), its not working and threw exception like "System.ArgumentException: 'Duplicate Controller with DuplicateControllerName:NopAjaxCartShoppingCart is already added'".
Here/below is my Code for configure method in startup file:
public void Configure(IApplicationBuilder app)
{
var dataSettings = DataSettingsManager.LoadSettings();
if (!dataSettings?.IsValid ?? true)
return;
var rewriteOptions = new RewriteOptions()
.AddRewrite("oauth/(.*)", "connect/$1", true)
.AddRewrite("api/token", "connect/token", true);
app.UseRewriter(rewriteOptions);
app.UseRouting();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
//register all routes
EngineContext.Current.Resolve<IRoutePublisher>().RegisterRoutes(endpoints);
});
}

Uncaught ReferenceError: SwaggerUIBundle is not defined at window.onload

In my localhost, my swagger UI working well. localhost:3030/documentation
This UI was working on the server also but from today on the server it is not working https://digitalpathshalabd.com/documentation
Errors
I faced the same "SwaggerUIBundle is not defined" with a blank page. Also the problem only on server and not local. And it also had worked in the past.
Then when I ctrl+f5 the local swagger page, it then also appeared local.
For us it appeared the Configuration order was swapped.
For me the fix was moving app.UseRouting() after the swagger init
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Procedure Service V1");
c.RoutePrefix = "";
});
app.UseRouting();
I am using org.springdoc:springdoc-openapi-ui:1.6.9 version and was facing this problem.
I checked https://www.npmjs.com/package/swagger-ui and added maven dependency for a lower swagger-ui version 3.0.21
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>3.0.21</version>
</dependency>
I found that the "swagger-ui/index.html" does not reference "swagger-initializer.js" , instead its source code is present in index.html itself (this the boiler-plate referring to pet store)
So in my Spring boot classpath resources/public folder, I copied the older swagger dist index.html file (which has the initializer code) and did the following changes
Changed the url part to point to my api-docs url. (e.g. /v3/api-docs)
Added "swagger-ui" to the src references, so that the swagger bundles/js will be called successfully from my index.html
<script charset="UTF-8" src="./swagger-ui/swagger-ui-bundle.js"></script>
<script charset="UTF-8" src="./swagger-ui/swagger-ui-standalone-preset.js"> </script>
When I accessed index.html - http://{server}:{port}/index.html- I could access my local Open API doc.
Check your swagger middleware configured correctly?
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
services.AddControllers();
}
This adds the Swagger generator to the services collection.
In the Configure() method, let’s enable the middleware for serving the generated JSON document and the Swagger UI:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}

Swagger breaks when adding an API Controller to my Host Project in aspnetboilerplate

I downloaded a new .Net Core MVC project template from https://aspnetboilerplate.com/Templates, setup everything (database and restored nuget packages) and ran the Host application. All good as I get the Swagger UI going and can see all the standard services.
I then proceeded to create a simple API controller in the Host application:
[Route("api/[controller]")]
[ApiController]
public class FooBarController : MyAppControllerBase
{
public string HelloWorld()
{
return"Hello, World!";
}
}
And then Swagger fails to load the API definition:
Fetch error
Internal Server Error http://localhost:21021/swagger/v1/swagger.json
If I remove the Route and ApiController attributes, Swagger works again, but my new controller is not displayed. I can access it by going to http://localhost:21021/foobar/helloworld which is probably fine, but I'd like it to show up in Swagger UI.
Am I missing something?
This is how you should configure your Swagger in your "Configure(IApplicationBuilder app, IHostingEnvironment env)" method.
#region Swagger COnfiguration
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("swagger/v1/swagger.json", "Your class name");
c.RoutePrefix = string.Empty;
});
#endregion
And here will be your configureServices settings for swagger.
services.AddSwaggerGen(config =>
{
config.SwaggerDoc("v1", new Info
{
Title = "Title Here",
Version = "v1"
});
});

NSwag: 404 Not Found /swagger/v1/swagger.json on IIS

I have a basic asp.net core 2.1 web API. I installed NSwag.ASPNetCore nuget package.
here is my startup.cs. When I run this on IIS Express, swagger is working fine.
Once I deploy this to IIS, I am getting 404 not found.
Do I need to add a Path somewhere?
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddMvc();
// Add framework services.
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//Add Application Services
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSwaggerDocument();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUi3();
app.UseMvc();
}
}
As mentioned by Rico below: upgrading to nswag v13 should fix the issue (for me it worked).
For versions of nswag before v13:
I had the same problem and I found a solution here: NSwag Issue #1914
What you need to do is configure a 'transform to external path':
app.UseSwaggerUi3(config =>
{
config.TransformToExternalPath = (s, r) =>
{
string path = s.EndsWith("swagger.json") && !string.IsNullOrEmpty(r.PathBase)
? $"{r.PathBase}{s}"
: s;
return path;
};
});
This worked for me on my iisexpress and on iis.
Check if you do not use Virtual Path for the application. Swagger by default checks absolute path instead of
localhost:port/MyVirtualPath/swagger/v1/swagger.json
It may happen when you use IIS server with virtual path delimiter.

Ambiguites in AspNet Core 2.0 using Swagger in Web API

I am trying to use Swagger in an AspNet Core 2 Web API. I have one sample that works based on:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
However, when I try to use the same approach in another service I get compile error:
2>Startup.cs(41,17,41,27): error CS0121:
The call is ambiguous between the following methods or properties:
'Microsoft.AspNetCore.Builder.SwaggerBuilderExtensions.UseSwagger(Microsoft.AspNetCore.Builder.IApplicationBuilder,
System.Action)'
and
'Microsoft.AspNetCore.Builder.SwaggerBuilderExtensions.UseSwagger(Microsoft.AspNetCore.Builder.IApplicationBuilder,
string, System.Action)'
2>Done building project "SocialNetwork.Api.csproj" -- FAILED.
The target call is in Startup.cs in the Configure method.
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(); // Ambiguous
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "SocialNetwork API V1");
});
app.UseMvc();
}
Does anyone have insight on this? Any help would be greatly appreciated.
Thank you.
I uninstalled Swagger and just installed the SwashBuckle.AspNetCore because it already implements the Swagger object inside. that is why it is calling ambigious.
Could it be that you have references to multiple Swagger-libraries? In my case I had accidentally added a reference to other swagger-related Nuget packages, and that caused the same error as you described.
Just uninstall the Swagger nugget package and you should be fine

Resources