问题描述: 在ASP.NET MVC项目中使用Swashbuckle生成API文档时,Swashbuckle无法识别任何控制器。
解决方法:
确保Swashbuckle及其依赖项已正确安装到项目中。可以通过NuGet包管理器或手动添加引用来安装Swashbuckle。
在Global.asax.cs文件中注册Swagger配置。在Application_Start方法中添加以下代码:
protected void Application_Start()
{
// ...
GlobalConfiguration.Configure(WebApiConfig.Register);
// Register Swashbuckle
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "My API");
})
.EnableSwaggerUi();
}
[RoutePrefix("api/users")]
public class UsersController : ApiController
{
// ...
[HttpGet]
[Route("{id}")]
public IHttpActionResult GetUser(int id)
{
// ...
}
// ...
}
public static void Register(HttpConfiguration config)
{
// ...
// Enable attribute routing
config.MapHttpAttributeRoutes();
// ...
}
确保项目中的所有依赖项已正确安装,并且项目能够成功构建。
启动项目并访问Swagger UI,以查看是否能够正确显示API文档。访问地址通常为:http://localhost:{port}/swagger
如果仍然无法识别控制器,请检查项目中是否存在其他可能导致冲突的配置或代码。