Blazor Swagger:无法加载 API 定义。获取错误:未定义 /swagger/v1/swagger.json

Posted

技术标签:

【中文标题】Blazor Swagger:无法加载 API 定义。获取错误:未定义 /swagger/v1/swagger.json【英文标题】:Blazor Swagger: Failed to load API definition. Fetch error: undefined /swagger/v1/swagger.json 【发布时间】:2020-06-06 17:12:00 【问题描述】:

我使用 .NET Core 3.1.200-preview-014977、Blazor、Swagger UI 5.0.0、我的依赖项

我遵循https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio 的指南。这是我的配置

using foo.Areas.Identity;
using foo.Controllers;
using foo.Data;
using Demo.Blazor;
using DevExpress.Blazor.DocumentMetadata;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System.Globalization;
using System.Net.Http;
using Microsoft.OpenApi.Models;
using System;

namespace foo


    public class Startup
    

        public Startup(IConfiguration configuration)
        
            Configuration = configuration;
        

        public IConfiguration Configuration  get; 

        public void ConfigureServices(IServiceCollection services)
        
            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("vi-VN");
            services.AddServerSideBlazor().AddCircuitOptions(options =>  options.DetailedErrors = true; );
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();          
            services.AddRazorPages().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
            services.AddRazorPages().AddRazorPagesOptions(options =>
            
                //options.Conventions.AuthorizePage("/currencies");
                //options.Conventions.AuthorizeFolder("/accounts");  
            );
            services.AddServerSideBlazor();
            services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
            services.AddSingleton<WeatherForecastService>();
            services.AddDocumentMetadata((serviceProvider, registrator) =>
            
                DemoConfiguration config = serviceProvider.GetService<IOptions<DemoConfiguration>>().Value;
                config.RegisterPagesMetadata(registrator);
            );
            services.AddMvc();
            services.AddHealthChecks();
            services.AddHttpClient();
            services.AddScoped<HttpClient>((sp) => 
                var httpClient = sp.GetService<IHttpClientFactory>().CreateClient();
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                return httpClient;
            );
            services.AddDevExpressBlazor();
            services.AddControllers();
            services.AddSwaggerGen(c =>
            
                c.SwaggerDoc("v1", new OpenApiInfo  Title = "My API", Version = "v1" );
            );
        

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        
            // 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", "My API V1");
            );

            if (env.IsDevelopment())
            
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            
            else
            
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            
            app.UseHttpsRedirection();
            app.UseStaticFiles();           
            app.UseRouting();
            app.UseAuthentication();
            //app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            
                endpoints.MapControllers();
                endpoints.MapRazorPages();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
                endpoints.MapHealthChecks("/health");
            );
        
    


我发现错误:

未能加载 API 定义。

如何解决?

【问题讨论】:

【参考方案1】:

应该是这样的

        app.UseSwaggerUI(c =>
       
           c.SwaggerEndpoint("v1/swagger.json", "My API V1");
       );

【讨论】:

使用这些代码sn-p后,我可以访问什么URL查看结果?我去localhost:44333/swagger/index.html,错误是一样的。 是的,这是应该可以访问的 URL。错误是否指向“undefined v1/swagger.json”? 不,这是错误信息,请参阅i.stack.imgur.com/NT4y6.png

以上是关于Blazor Swagger:无法加载 API 定义。获取错误:未定义 /swagger/v1/swagger.json的主要内容,如果未能解决你的问题,请参考以下文章

Swagger 未加载 - 无法加载 API 定义:获取错误未定义

Azure 静态 Web 应用 Blazor WASM .Net Core API 和标识 - 无法从“_configuration”加载设置

加载 API 定义失败,获取错误:未定义 /swagger/v1/swagger.json

Blazor 项目在本地构建,但不在 azure 管道中

Springfox swagger-ui.html无法推断基本URL - 由丢失的cookie引起

无法从 Blazor WebAssembly 应用本地访问 Azure Function Api