ASP.NET Core 覆盖 Swagger index.html 默认路由

问题描述 投票:0回答:2

我正在使用 ASP Net Core Web App 和 Razor Pages。我正在努力将 index.html Swagger 作为主/默认页面。当应用程序启动时 -> 自动转发到 Swagger。我还在 Azure 上托管我的应用程序 - 在该托管环境中也存在同样的问题,Swagger 是主页。当您从主 URL 转发到 swagger 时,这是从 Internet 访问站点的问题。 .NET 中的新示例项目未访问 index.html。

我需要将默认页面和根“/”从 Swagger 更改为我选择的页面。

下面是我的 Program.cs 示例以及访问我的页面的结果。

程序.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 = "[email protected]",
            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();

当我尝试访问主 URL 时发生了什么:

我尝试添加:

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

还尝试删除 Swagger,但没有任何帮助。

asp.net-core swagger
2个回答
1
投票

您可以尝试设置一个默认页面,为访问者提供使用此中间件的网站起点:

app.UseDefaultFiles()
, 您可以查看此文档了解更多详细信息

如果你不想在调试时自动前进 Swagger,你可以修改你的 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"
      }
    },

并尝试删除

c.RoutePrefix = string.Empty;
中的

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwimmingSchool");
    c.RoutePrefix = string.Empty;
}

在我的情况下,我尝试如下(index.html 不在 wwwroot 下):

       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 = ""
            }); 

结果:


-1
投票

实际上为我工作,将文件移动到新创建的项目,而无需安装 Swashbuckle Swagger。对我来说,Swagger 不是必需品,它解决了所有路由问题。

© www.soinside.com 2019 - 2024. All rights reserved.