.NetCore Swagger can not work - asp.net-core

I took long time to try to configure swagger for my .netCore project.
the following steps I have done, but not successful :-(
Nuget Package:
Swashbuckler.SwaggerGen,
Swashbuckler.SwaggerUi,
in ConfigureServices Method
instance.AddMvc();
instance.AddSwaggerGen();
in Config Method
instance.UseMvc();
instance.UseSwagger();
instance.UseSwaggerUi();
I rebuild my project, and go to link http://localhost:5000/swagger/ui
came error: localhost refused to connect.ERR_CONNECTION_REFUSED
Can anybody help me??
BR,
Leon

This is what I have in my aspnet core rest api project.
In ConfigureServices method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Title = "MyProject - HTTP API",
Version = "v1",
Description = "My project HTTP API."
});
});
In the Configure method:
app.UseSwagger().UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProj HTTP API v1");
});
Then simply navigate to http://localhost:56468/swagger/ where 56468 is the port my application is running on.

You should include NuGet package Swashbuckle.AspNetCore for swagger configuration. Add below code in Configure section of Startup.cs
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
And add below code in ConfigureServices section of Statup
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo() { Title = "My API", Description = "My API V1" });
});

Related

swagger not working with gRPC .net core 7

I followed the steps this documentation https://learn.microsoft.com/en-us/aspnet/core/grpc/json-transcoding-openapi?view=aspnetcore-7.0 and integrated google protos.
I tried to open it locally and adding /swagger/index.html
and I am getting
An HTTP/1.x request was sent to an HTTP/2 only endpoint.
Program.cs:
using Extensions;
using Google.Api;
using gRPCserver.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.OpenApi.Models;
using Models.Models;
using Serilog;
using Serilog.Sinks.Kafka;
using sKashCallCenterAPI.Interface;
using sKashCallCenterAPI.Service;
var builder = WebApplication.CreateBuilder(args);
var ConnectionString = builder.Configuration["sqlconnection:ConnectionString"];
builder.Services.AddDbContext<sKashDbContext>(options =>
{
options.UseSqlServer(ConnectionString);
});
//builder.Services.AddGrpc();
builder.Services.AddGrpcSwagger();
builder.Services.AddGrpcHttpApi();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo { Title = "gRPC Server", Version = "v1" });
var filePath = Path.Combine(System.AppContext.BaseDirectory, "gRPCserver.xml");
c.IncludeXmlComments(filePath);
c.IncludeGrpcXmlComments(filePath, includeControllerXmlComments: true);
});
ConfigurationManager configuration = builder.Configuration;
var kafkaServer = configuration["KafkaConfig:ServerIP"] + ":" + configuration["KafkaConfig:Port"];
builder.Host.UseSerilog((ctx, lc) => lc
.WriteTo.Console()
.WriteTo.Kafka(topic: configuration["KafkaConfig:Topic"], bootstrapServers: kafkaServer)
.Enrich.WithProperty("Source", configuration["KafkaConfig:Source"])
.ReadFrom.Configuration(ctx.Configuration));
builder.Services.ConfigurJWTAuthentication();
builder.Services.ConfigureRepositoryWrapper();
builder.Services.ConfigureContractsServices();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IMemoryCache, MemoryCache>();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
// Configure the HTTP request pipeline.
//app.MapGrpcService<GreeterService>();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
});
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
app.Run();
The project is running but no swagger documentation is shown.
Assuming you're debugging using Kestrel, did you configure its protocol support for both HTTP1 and HTTP2 in appsettings or the startup pipeline?
{
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1AndHttp2"
}
}
}
Yes, you are right. The swagger documentation will not show up as default. You will have to use a plugin as grpc-gateway. This is a reverse-proxy server which translates a RESTful HTTP API into gRPC, by reading protobuf service definitions.

How swagger authentication works?

Hi I have developed swagger UI for my .net core web application. I have added authentication to it. I have registered two applications in my Azure AD. One for Swagger and one for Back end .Net core app. Below is my code.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = swaggerUIOptions.AuthorizationUrl,
TokenUrl = swaggerUIOptions.TokenUrl
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new[] { "readAccess", "writeAccess" } }
});
});
In the above code I am indicating type and flow. Also specifying AuthorizationUrl and token url. When coming to scopes, If I add scopes then that means my Swagger has access to added scopes or my back end api has access to those scopes? Then I have below code.
c.OAuthClientId(swaggerUIOptions.ClientId);
c.OAuthClientSecret(swaggerUIOptions.ClientSecret);
c.OAuthRealm(azureActiveDirectoryOptions.ClientId);
c.OAuthAppName("Swagger");
c.OAuthAdditionalQueryStringParams(new { resource = azureActiveDirectoryOptions.ClientId });
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
When we develop swagger, We are getting access token for swagger app or back end app? Also I have c.OAuthRealm and passing my back end app client id. What this line of code do actually? Also when I add [Authorize] attribute in top of my API and then If i try to hit api directly It will not work. It will work only after authentication. So how Authorize attribute works exactly? Can someone help me to understand these things? Any help would be appreciated. Thanks
Regarding how to configure Swagger to authenticate against Azure AD, please refer to the following steps
Configure Azure AD for your web API. For more details, please refer to the document
a. Create Azure AD web api application
b. Expose API
c. Configure code
config file
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",
"TenantId": "<your tenant id>"
},
Add following code in the Stratup.cs
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
Configure swagger. For more details, please refer to the blog.
a. Create Azure Web application
b. Configure API permissions. Regarding how to configure, you can refer to the document
c. code
Install SDK
<PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
Add the following code to Startup.cs in the ConfigureServices method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = $"https://login.microsoftonline.com/{Configuration["AzureAD:TenantId"]}/oauth2/authorize",
Scopes = new Dictionary<string, string>
{
{ "user_impersonation", "Access API" }
}
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new[] { "user_impersonation" } }
});
});
Add the following code to the Configure method:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.OAuthClientId(Configuration["Swagger:ClientId"]);
c.OAuthClientSecret(Configuration["Swagger:ClientSecret"]);
c.OAuthRealm(Configuration["AzureAD:ClientId"]);
c.OAuthAppName("My API V1");
c.OAuthScopeSeparator(" ");
c.OAuthAdditionalQueryStringParams(new { resource = Configuration["AzureAD:ClientId"] });
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

IdentityServer - How to bypass authorization for simple debug

I have several .NET core API and I use IdentityServer 4 as a seperate service for authentication.
The problem is that in "debug" I also wish to run my API without authentication (without launching the IdentityServer).
So, I try to bypass it... I have try several solutions, but none work:
- With a AuthorizationHandler: Bypass Authorize Attribute in .Net Core for Release Version
- With a Middleware : Simple token based authentication/authorization in asp.net core for Mongodb datastore
- With a filter : ASP.NET Core with optional authentication/authorization
- With AllowAnonymousFilter : Bypass Authorize Attribute in .Net Core for Release Version
But no way, none of theses solutions work, I still got a "401 Undocumented Error: Unauthorized" !
Here is some parts of my code:
public void ConfigureServices(IServiceCollection services)
{
// JSON - setup serialization
services.AddControllers().
AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(new TargetSpot.Core.Json.SnakeCaseNamingStrategy()));
options.JsonSerializerOptions.IgnoreNullValues = true;
});
// Force lowercase naming
services.AddRouting(options => options.LowercaseUrls = true);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Setup the connection to the IdentityServer to request a token to access our API
services.AddAuthentication(IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = Configuration.GetSection("APISettings")["AuthorityURL"];
options.RequireHttpsMetadata = false;
options.ApiName = Configuration.GetSection("APISettings")["APIName"];
});
// Add swagger
services.AddSwaggerGen(options =>
{
//options.DescribeAllEnumsAsStrings();
options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "HTTP API",
Version = "v1",
Description = "The Service HTTP API",
TermsOfService = new Uri("http://www.myurl.com/tos")
});
// XML Documentation
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger().UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Winamp API v1");
});
}
I had similar problem.
AllowAnonymousFilter works in ASP.NET Core 2.2 but not in ASP.NET Core 3.x.
After day of investigation I have found out that switching from UseEndpoints to UseMvc solved it and I can now disable authentication without commenting out [Authorize] attributes.
It seems that UseEndpoints does not use filter when registered by AddMvc but how to correctly register it when using UseEndpoints I do not know.
My solution
Startup.ConfigureServices:
services.AddMvc(o =>
{
o.EnableEndpointRouting = false;
o.Filters.Add(new AllowAnonymousFilter());
});
Startup.Configure:
// anonymous filter works with UseMvc but not with UseEndpoints
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllerRoute(
// name: "default",
// pattern: "{controller=Home}/{action=Index}/{id?}");
//});
I found the solution in this link: https://docs.identityserver.io/_/downloads/en/latest/pdf/. Obviously I had to remove the Authorize attributes I added manually in my controllers.
app.UseEndpoints(endpoints =>
{
// Allowing Anonymous access to all controllers but only in Local environment
if (env.IsEnvironment(Constants.ApplicationConstants.LocalEnvironment))
endpoints.MapControllers();
else
endpoints.MapControllers().RequireAuthorization();
});

Asp.net core swagger not found and server error

I have installed Swashbuckle.AspNetCore version 4.0.1 and tried all solutions and ways. Maybe this is duplicate it's not working in IIS.
I always get not found error or internal server error.
This is my Startup.cs.
// Configure Services
services.AddSwaggerGen(x =>
{
x.SwaggerDoc("v1", new Info { Title = "Shop API", Version = "v1" });
});
// Configure
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
//c.RoutePrefix = string.Empty;
});
app.UseMvc();
Did anybody tried latest version?
I'm using the same version as your. Mine below config look like this
ConfigureServices
// Register the Swagger generator, defining one or more Swagger documents
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "Awesome CMS Core API V1",
Contact = new Contact { Name = "Tony Hudson", Email = "", Url = "https://github.com/ngohungphuc" }
});
c.SwaggerDoc("v2", new Info
{
Version = "v2",
Title = "Awesome CMS Core API V2",
Contact = new Contact { Name = "Tony Hudson", Email = "", Url = "https://github.com/ngohungphuc" }
});
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
});
Configure
// Enable middleware to serve generated Swagger as a JSON endpoint.
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", "Awesome CMS Core API V1");
c.SwaggerEndpoint($"/swagger/v2/swagger.json", "Awesome CMS Core API V2");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
I'm just having 2 API version so it's not important in your case
Make sure your middleware are in correct order like mine
Please let me know if you have any problem

Swashbuckle root error when i deploy on subfolder

I begin with Swashbuckle, i make a Web API in .NET Core with Swashbuckle.
I need to deploy my API in a sub-application of an IIS site
IIS infrastructure
IIS Site (site)
myApi (subApplication)
http://ip:80/myApi
I would like the access to swagger UI to be done via this url :
http://ip:80/myApi/swagger
I would like the access to the methods to be done by this url :
http://ip:80/myApi/api/[controller]/methode
ConfigureServices(IServiceCollection services)
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My REST API", Version = "v1" });
});
Configure(IApplicationBuilder app..)
if (env.IsEnvironment("ProdIT"))
{
app.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = "/myApi/");
c.RouteTemplate = "myApi/api-docs/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "myApi/swagger";
c.SwaggerEndpoint("/myApi/api-docs/v1/swagger.json", "MY REST API V1");});
Route Controller
[Route("api/[controller]")]
Could you tell me what's wrong with my code?
Thanks in advance
I had the same issue and I resolved it by configuring the SwaggerUI like that;
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "MY REST API V1");});
}