1

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 : UrlForwarding

I tried add:

options.Conventions.AddPageRoute("/Index.html", "");

Also tried to remove Swagger and nothings helped :(

Kelaran
  • 9
  • 2

2 Answers2

1

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:

enter image description here

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11
  • At first, thx so much for answering my question :) I applied this solution but still index.html is main page after launch app and after enter {project_url}. Can i override index.html with proper .cshtml file ? – Kelaran Nov 02 '22 at 08:40
  • Deleting root from swagger resolves problem with swagger ;) now swagger is accessible only from swagger/index.html :) thx. – Kelaran Nov 02 '22 at 08:54
  • "Can i override index.html with proper .cshtml file" .cshtml files are not staticfiles,so it won't work – Ruikai Feng Nov 02 '22 at 08:57
  • If my answer could solve your question could you accepte it to help more people with the same problem? – Ruikai Feng Nov 02 '22 at 08:59
  • If you want override index.html with index.cshtml file just remove the middleware app.UseDefaultFiles(options); and Delete root from swagger – Ruikai Feng Nov 02 '22 at 10:01
  • Problem is only half-resolved. I change path to Swagger, but still index.html is a starting page when app starts and in root path ("/"). Removing middleware app,UseDefaultFiles(options); and also app.UseStaticFiles(); dont solve the problem of targeting index.html as default. How override index.html at start with index.cshtml ? On the azure is only possibility to override with physical document :( :( maybe i will need an api gateway to forward this url. Maybe some other ideas how force app to set virtual path /Home for example instead of /index.html ? – Kelaran Nov 02 '22 at 11:48
0

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.

Kelaran
  • 9
  • 2