我正在尝试设置我的 web api 项目以使用 Swagger。
我安装了 Swashbuckle,当我转到 http://localhost:55010/swagger
时,Swagger UI 可以正常工作,但我看不到任何 Controller 操作。
我正在为我的操作使用这种路径:http://localhost:55010/api/v1/Role
我目前只有一个版本的 api,但我计划拥有多个版本,所以我在我的 URL 路径中使用 v1
(它是通过使用我的 Controllers 文件夹中的子文件夹设置的).
这是我访问 http://localhost:55010/swagger/docs/v1
时看到的内容:
{"swagger":"2.0","info":{"version":"v1","title":"Swashbuckle Dummy API V1"},"host":"localhost:55010","schemes":["http"],"paths":{},"definitions":{}}
这是我正在使用的配置:
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.MultipleApiVersions(
(apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
(vc) =>
{
//vc.Version("v2", "Swashbuckle Dummy API V2");
vc.Version("v1", "Swashbuckle Dummy API V1");
});
})
.EnableSwaggerUi(c =>
{
});
}
private static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
{
// I don't know how I am supposed to use this
return true;
}
}
我的路线配置:
config.Routes.MapHttpRoute(
name: "WithActionApi",
routeTemplate: "api/{folder}/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { action = @"[A-Za-z]+" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{folder}/{controller}/{id}",
defaults: new { action = "DefaultAction", id = RouteParameter.Optional }
);
和一个 Controller 的例子:
public class GridTemplateController : BaseController
{
GridTemplateLogic logic;
public GridTemplateController(IPermissionValidator permissionValidator, IRolePermissionLogic logicRolePermission)
: base(permissionValidator, logicRolePermission)
{
logic = new GridTemplateLogic(new GridTemplateRepository(ConnectionString, CurrentUser), permissionValidator);
}
// GET: api/v1/GridTemplate/ForGrid/5
[HttpGet]
public IHttpActionResult ForGrid(int id)
{
try
{
var entityList = logic.GetAllByGridId(id);
return Ok(new ApiResponse(entityList));
}
catch (UnauthorizedAccessException)
{
return Unauthorized();
}
}
...........
最佳答案
将 swagger 配置更改为:
public class SwaggerConfig
{
public static void Register(HttpConfiguration config)
...
}
并在所有其他配置之后配置它:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
...
SwaggerConfig.Register(config);
}
关于c# - 在 Swagger UI 中看不到我的 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227782/