问题: Swagger在我的.NET WebAPI项目中运行良好,但未列出任何API端点。
这是我得到的:http://localhost:62536/swagger/docs/v1
{
"swagger":"2.0",
"info":{
"version":"v1",
"title":"Backend.WebApi"
},
"host":"localhost:62536",
"schemes":[
"http"
],
"paths":{
},
"definitions":{
}
}
swaggerConfig.cs
using System.Web.Http;
using WebActivatorEx;
using Backend.WebApi;
using Swashbuckle.Application;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace Backend.WebApi
{
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "Backend.WebApi");
})
.EnableSwaggerUi(c =>
});
}
}
}
这是一个控制器示例:
testController.cs
namespace Backend.WebApi.Controllers
{
[Authorize]
[RoutePrefix("api/test")]
public class TestController : ApiController
{
private readonly IAppService _appService;
public TestController(IAppService appService)
{
_appService = appService;
}
[Route("vehicles/all")]
public List<VehicleViewModel> GetVehicles()
{
return _appService.GetVehicles();
}
[...]
我也试过启用XML评论(因为我的应用程序中有一些),但列表中没有弹出任何内容。 我错过了什么吗? 感谢。
更新
webConfigApi.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
AutoMapperConfiguration.Configure();
SwaggerConfig.Register();
ConfigureIoC(config);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
swaggerConfig.cs
// [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace Backend.WebApi
答案 0 :(得分:1)
将配置部分从SwaggerConfig.cs
移至WebApiConfig.cs
解决了问题,原因可能是我们在项目中使用了OWIN
。
<强> webApiConfig.cs 强>
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
[...]
config
.EnableSwagger(c => c.SingleApiVersion("v1", "Backend.WebApi"))
.EnableSwaggerUi();
答案 1 :(得分:0)
我认为你错过了WebApiConfig.cs中的以下行
public static void Register(HttpConfiguration config)
{
...
config.MapHttpAttributeRoutes();
...
}
它将注册您的网络API的所有路线。