Swashbuckle - How do I change the displayed title of the service? - asp.net-core

When I run a .NET Core service using swashbuckle, the title it displays (above all the resources) is derived from the assembly name.
How can I specify my own title to appear on the swagger page?
(The title displayed on the page is distinct from the document title, which can be modified via options.DocumentTitle passed into the app.UseSwaggerUI() method.)
edit: This is my current setup code - it's what comes out of the box with the C# webapi template:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

builder.Services.AddSwaggerGen(opt => opt.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "Title of the service",
Description = "Description of the service"
}));

Related

Blazor, windows account and AzureAD/Microsoft Identity Platform login automatic?

If I create a new Blazor server application, choose to use Microsoft Identity Platform and connect to our work.
When I run that application without any changes, my windowsaccount log in and my name/mailadress at work shows on top on screen.
I have an old project where I got this behavior before but last week the project doesn't logged in with my workaccount automatic anymore, I need to push login button and then my Blazor server app login in with my workaccount automatic.
What I know I haven't change any code that connect to AzureAD last week. What code is it in a fresh Blazor Server application that are configure with Microsoft Identity Platform that make an automatic login if you are logged in with a microsoft account on your computer?
My Program.cs that don't login automatic anymore.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
builder.Services.AddRazorPages();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
//options.FallbackPolicy = options.DefaultPolicy;
options.AddPolicy("Admin", policy => policy.RequireClaim("role", "Admin"));
});
builder.Services.AddAutoMapper(typeof(Program));
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
}, ServiceLifetime.Transient);
builder.Services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
..
builder.Services.AddHttpClient();
builder.Services.AddHttpContextAccessor();
builder.Services.AddControllers();// Add support for API controllers
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Blazor API V1");
});
}
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();

.ASP NET Core override Swagger index.html default routing

Im using ASP Net Core Web App with Razor Pages. Im struggling with index.html Swagger as main/default page. When App Starts -> automatically forwards to Swagger. Im also hosting my app on Azure - same problem in that hosting env, Swagger is main page. This is problem for accessing site from Internet when u are forwarded from main url to swagger. Fresh example project from .NET is not accessing index.html.
I need to change default page and root "/" from Swagger to page i choose.
Below sample of my Program.cs and result of accessing my page.
Program.cs
`using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using SwimmingSchool.Repositories;
using SwimmingSchool.Repositories.Interfaces;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Microsoft.AspNetCore.Mvc.Authorization;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var config = builder.Configuration;
// Frontend services
services.AddRazorPages().AddMicrosoftIdentityUI();
services.AddMvc().AddRazorPagesOptions(opt => {
opt.RootDirectory = "/Frontend";
});
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
// Authentication services
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(config.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(Environment.GetEnvironmentVariable("DownstreamApi:Scopes")?.Split(' '))
.AddMicrosoftGraph(config.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
//Database services
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDbContext<SwimmingSchoolDbContext>(options => options.UseSqlServer(Environment.GetEnvironmentVariable("SwimmingSchoolDb")));
//Scoped services
services.AddScoped<ICustomersRespository, CustomersRepository>();
//Swagger services
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "SwimmingcSchool",
Description = "Company application for manage swimming school",
TermsOfService = new Uri("http://SwimmingSchool.pl"),
Contact = new OpenApiContact
{
Name = "Biuro",
Email = "biuro#SwimmingSchool.pl",
Url = new Uri($"http://swimmingschool.pl"),
}
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
//c.IncludeXmlComments(xmlPath);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// 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.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwimmingSchool");
c.RoutePrefix = string.Empty;
}
);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
app.Run();`
Here what is happening when i try to access main url :
I tried add:
options.Conventions.AddPageRoute("/Index.html", "");
Also tried to remove Swagger and nothings helped :(
You could try to Set a default page which provides visitors a starting point on a site with this middleware:app.UseDefaultFiles(),
you could check this document for more details
And if you don't want going forward Swagger automaticlly when you debug,you could modify your launchSettings.json :
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
//modify launchUrl to "" , you could modify it when you debug with Kestrel as well
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
and try to remove c.RoutePrefix = string.Empty; in
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwimmingSchool");
c.RoutePrefix = string.Empty;
}
I tried as below(index.html was not under wwwroot) in my case:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger v1");
//c.RoutePrefix = String.Empty;
});
}
app.UseHttpsRedirection();
var provider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "StaticFile"));
var options = new DefaultFilesOptions() { FileProvider=provider};
options.DefaultFileNames.Add("Index.html");
app.UseDefaultFiles(options);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = provider,
RequestPath = ""
});
Result:
Actually worked for me move files to new-created project without installing Swashbuckle Swagger. For me Swagger isn't nesesery and solves all problem with routing.

How to set default identity login page in .net core 6 mvc instead of index page in program.cs

I am developing web app with .net core 6. How can I set default page to Identity Login page instead of index page in program.cs. Below is my program.cs code
using Microsoft.EntityFrameworkCore;
using ASPNETCOREPRJ.Areas.Identity.Data;
using ASPNETCOREPRJ.Data;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DBContextConnection");builder.Services.AddDbContext<DBContext>(options =>
options.UseSqlServer(connectionString));builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DBContext>();
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// 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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();```
You can change your code to:
builder.Services.AddControllersWithViews().AddRazorPagesOptions(options => {
options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "");
});

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

ASP.NET Core Swagger not working in Chrome with CORS error

I've been following the help for ASP.NET Web API Help Pages using Swagger and I receive the following error in Chrome:
Can't read from server. It may not have the appropriate access-control-origin settings.
It works in IE10 however it doesn't appear to pick up changes.
I found the following entry Can't read swagger JSON from http://localhost:9000/api-docs/ unfortunately it refers to changing it under grunt when it now works under gulp.
I've also tried to change the CORS setting in ASP.NET core:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
// Inject an implementation of ISwaggerProvider with defaulted settings applied
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Status API",
Description = "A simple example ASP.NET Core Web API!",
TermsOfService = "None",
Contact = new Contact { Name = "A Persone", Email = "some-support#some-company.com", Url = "http://www.some-company.com/" },
License = new License { Name = "Use under LICX", Url = "http://url.com" }
});
});
services.AddCors(options =>
{
options.AddPolicy("AnyOrigin", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod();
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
app.UseCors("AnyOrigin");
}
Unfortunately that doesn't make any difference.
Suggestion on how to solve it by changing the gulp settings or the .NET changes would be very welcome
Usually this should do the trick, you just need it to have the same policy name. I don't think adding the filters is necessary, if you want to apply it to all requests/routes.
// ConfigureServices
services.AddCors(options =>
{
options.AddPolicy("AnyOrigin", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod();
});
});
// Configure
app.UseCors("AnyOrigin");
// Register other middleware here, like UseMvc or UseStaticFiles, depending on if you
// want StaticFiles to be affected by cors or not you put it before or after the UseCors call
Update
Like mentioned in the comments above, the middlewares are executed in the order in which they are registered. The request reaches your APi controller before the Cors middleware ever receives it.
Your Configure method has to look like this instead:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
// it must be placed before UseMvc and before or after
// UseStaticFiles, depending on if you want the static files to be
// Cors enabled or not
app.UseCors("AnyOrigin");
app.UseMvc();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
}