首页 > 解决方案 > 停止 swagger 在 ASP.net Core 5 MVC 应用程序中作为启动页面加载

问题描述

我正在构建一个与 Swagger 集成的 ASP.net Core 5 MVC 应用程序。我使用 Nuget Swashbuckle.AspNetCore.Swagger 版本 6.1.3

这是写这篇文章的最新日期。现在我有两个问题:

  1. 无论我在 startup.cs 文件中进行什么配置,Swagger 始终将其页面加载为启动页面。应用程序总是从:http://localhost:port/index.html 开始(不知道这个路由是从哪里发生的??!!)
  2. 我想从http://www.url.com/home/index启动应用程序,然后当用户键入http://www.url.com/swagger时,开始显示招摇页面。

以下是我配置我的 startup.cs 的方式,如果有人能告知我的配置有什么问题:

using MYAPIDataModels.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.Text.Json.Serialization;
using System.Text.Encodings.Web;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Mvc;
using MYAPIServer.Models.Swagger;
using Microsoft.AspNetCore.Mvc.Versioning;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using MYAPIServer.Data;

namespace MYAPIDataModels
{
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IMYAPIServerConnector, MYAPIServerConnector>();

        services.AddControllersWithViews()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.PropertyNamingPolicy = null;
                    options.JsonSerializerOptions.WriteIndented = true;
                    //options.JsonSerializerOptions.IgnoreNullValues = true;
                    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
                    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                    options.JsonSerializerOptions.MaxDepth = 256;
                });

        // https://www.youtube.com/watch?v=rQqsII9iyPk

        services.AddApiVersioning(options =>
        {
            // https://www.learmoreseekmore.com/2019/11/aspnet-core-web-api-versioning.html
            // to allow accessing controllers with no versioning (like Home or Login).
            //options.UseApiBehavior = false;
            options.AssumeDefaultVersionWhenUnspecified = true;
            options.ReportApiVersions = true;
            options.DefaultApiVersion = new ApiVersion(1, 0);

            // https://www.thecodebuzz.com/api-versioning-in-asp-net-core-with-examples/
            //options.ApiVersionReader = new UrlSegmentApiVersionReader();
            options.ApiVersionReader = new MediaTypeApiVersionReader("v");
        });

        services.AddSwaggerGen(options =>
                {

                    /* https://dotnetthoughts.net/openapi-and-versioning-asp-net-core/
                    ** Following code to avoid swagger generation error
                    ** due to same method name in different versions.   */

                    options.ResolveConflictingActions(descriptions => descriptions.First());

                    options.SwaggerDoc("v1", new OpenApiInfo { 
                    Title = "MYAPI API",
                    Description  = "MYAPI Web API",
                    Version = "v1"
                    });

                    options.SwaggerDoc("v2", new OpenApiInfo
                    {
                        Title = "MYAPI API",
                        Description = "MYAPI Web API",
                        Version = "v2"
                    });

                    // https://dev.to/htissink/versioning-asp-net-core-apis-with-swashbuckle-making-space-potatoes-v-x-x-x-3po7
                    // https://dev.to/codeswayslay/comment/paff

                    options.DocInclusionPredicate((version, desc) =>
                    {
                        if (!desc.TryGetMethodInfo(out MethodInfo methodInfo))
                            return false;

                        var versions = methodInfo.DeclaringType
                        .GetCustomAttributes(true)
                        .OfType<ApiVersionAttribute>()
                        .SelectMany(attr => attr.Versions);

                        var maps = methodInfo
                        .GetCustomAttributes(true)
                        .OfType<MapToApiVersionAttribute>()
                        .SelectMany(attr => attr.Versions)
                        .ToArray();

                        return versions.Any(ver => $"v{ver}" == version)
                        && (!maps.Any() || maps.Any(ver => $"v{ver}" == version));
                    });

                    options.OperationFilter<RemoveVersionFromParameter>();
                    options.DocumentFilter<ReplaceVersionWithExactValueInPath>();
                });

        services.AddDbContext<MYAPIServerContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("MYAPIServerContext")));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

        }
        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.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseSwagger();
        app.UseSwaggerUI(options => {
            options.SwaggerEndpoint("./swagger/v1/swagger.json", "Swagger for MYAPI Web API V1");
            options.SwaggerEndpoint("./swagger/v2/swagger.json", "Swagger for MYAPI Web API V2");
            options.RoutePrefix = string.Empty;
        });

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            //endpoints.MapControllers();
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            //endpoints.MapDefaultControllerRoute();
        });
    }
}

}

标签: c#asp.net-coreswaggervisual-studio-2019swagger-ui

解决方案


推荐阅读