我使用.NETCore 3.1.200-预览-014977, Blazor,SwaggerUI5.0.0,我的依赖项
我跟着导游https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1
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定义失败。
怎么修?
如果您的控制器之一缺少[Http*]属性,则可能会出现此问题。考虑以下代码:
[Route("[action]")]
public async Task<IEnumerable<IdentityRole>> GetRoles()
{
_logger.LogDebug("Getting roles");
return await _roleManager.Roles.ToListAsync();
}
您的应用程序可以正常工作,但Swagger不能。只是因为示例endpoint没有定义[Http*]属性,因此swagger将无法“解析”您的控制器。因此,您会看到“未能加载API定义。”错误消息。
在这种情况下,您将像这样添加[HttpGet]属性:
[HttpGet]
[Route("[action]")]
public async Task<IEnumerable<IdentityRole>> GetRoles()
{
_logger.LogDebug("Getting roles");
return await _roleManager.Roles.ToListAsync();
}
希望这能有所帮助!这可能不是您遇到的确切问题,但关键是如果您的控制器没有使用常见模式定义,swagger将无法识别它们。
祝你好运!
应该是这样的
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "My API V1");
});