我正在使用 Swagger 开发 ASP.NET Core 项目来获取 API 文档。但是,我遇到了一个问题,Swagger UI 没有按预期显示我的控制器,它只显示最少的 API。这是我的项目设置和我面临的问题的概述
它应该显示控制器端点,但它不显示它只显示最小的 API,为什么?
这是控制器端点 [![在此处输入图像描述][3]][3]
这是控制器代码
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using MyBGList.DTO;
namespace MyBGList.Controllers
{
[EnableCors("AnyOrigin")]
public class BoardGamesController : ControllerBase
{
private readonly ILogger<BoardGamesController> _logger;
public BoardGamesController(ILogger<BoardGamesController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetBoardGames")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 60)]
public RestDTO<List<BoardGame>> Get()
{
var restDTO = new RestDTO<List<BoardGame>>();
restDTO.Data = new List<BoardGame>
{
new BoardGame()
{
Id = 1,
Name = "Axis & Allies",
Year = 1981
},
new BoardGame()
{
Id = 2,
Name = "Citadels",
Year = 2000
},
new BoardGame()
{
Id = 3,
Name = "Terraforming Mars",
Year = 2016
}
};
restDTO.Links = new List<LinkDTO>
{
new LinkDTO(Url.Action(null, "BoardGames", null, Request.Scheme), "self", "GET")
};
return restDTO;
}
}
}
program.cs代码
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(config =>
{
config.AddDefaultPolicy(options =>
{
options.WithOrigins(builder.Configuration["AllowedOrigins"]);
options.AllowAnyHeader();
options.AllowAnyMethod();
});
config.AddPolicy(name: "AnyOrigin", options =>
{
options.AllowAnyOrigin();
options.AllowAnyHeader();
options.AllowAnyMethod();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
if (app.Configuration.GetValue<bool>
("UseDeveloperExceptionPage"))
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error");
}
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();
app.MapGet("/error", () => Results.Problem());
app.MapGet("/error/test", () =>
{
throw new
InvalidDataException();
});
app.MapGet("/cod/test", [EnableCors("AnyOrigin")]
[ResponseCache(NoStore = true)] () =>
Results.Text($@"
<html>
<head>
<title>JavaScript Test</title>
</head>
<body>
<script>
window.alert(`this is`)
</script>
<noscript>Your client does not support
JavaScript</noscript>
</body>
</html>",
"text/html")
);
app.MapDefaultControllerRoute();
app.MapControllers();
app.Run();
问题是你错误地忘记了添加ApiController的属性和route属性来定义控制器和路由。
如果您添加以下缺失内容,在您的控制器类中它将起作用:
[ApiController] <-- is missing in your code
[Route("[controller]")] <-- is missing in your code
[EnableCors("AnyOrigin")]
public class BoardGamesController : ControllerBase
etc...