我正在尝试使用SwaggerUI,但我遇到了一些问题。
当我致电http://mysite.com/api/swagger时,我明白了:
{
"apiVersion":"4.0.0.0",
"swaggerVersion":"2.0",
"basePath":"http://mysite.com",
"resourcePath":null,
"apis":
[
{
"path":"/api/docs/V1.Foo",
"description":"Foo V1.",
"operations":[]
},
{
"path":"/api/docs/V2.Foo",
"description":"Foo V2.",
"operations":[]
}
]
}
但是,当我致电http://mysite.com/api/docs/V1.Foo或http://mysite.com/api/docs/V2.Foo时,我得到了这个:
<Error>
<Message>
The requested resource does not support http method 'GET'.
</Message>
</Error>
看起来我正在调用我的API,但我正在尝试获取API文档。
我的所有控制器都实现了System.Web.Http.ApiController。
这是我的WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
config.Routes.MapHttpRoute(
name: "SwaggerApi",
routeTemplate: "api/docs/{controller}",
defaults: new { swagger = true }
);
config.Routes.MapHttpRoute(
name: "Swagger",
routeTemplate: "api/swagger",
defaults: new { controller = "swagger" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{version}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional, version = "v1" }
);
config.Filters.Add(new SwaggerActionFilter());
try
{
config.Services.Replace(typeof(IDocumentationProvider),
new XmlCommentDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/XmlDocument.XML")));
}
catch (FileNotFoundException)
{ }
//My version selector
config.Services.Replace(typeof(IHttpControllerSelector), new VersionControllerSelector(config));
config.Filters.Add(new VersionNoHeaderAttribute());
}
}
这是我的IHttpControllerSelector实现(VersionControllerSelector):
...
public HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
var routeData = request.GetRouteData();
if (routeData == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
string version;
if (GetRouteVariable<bool>(routeData, "swagger"))
{
version = ""; // Here I have the version and controller name.
}
else if (request.RequestUri.ToString().ToLower().EndsWith("swagger"))
{
version = "net."; // Net.Swagger
}
else
{
version = GetRouteVariable<string>(routeData, VersaoKey);
if (version == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
version = string.Format(CultureInfo.InvariantCulture, "{0}.", version); // V1.MyControler
}
var controllerName = GetRouteVariable<string>(routeData, ControllerKey);
if (controllerName == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var key = version + controllerName;
HttpControllerDescriptor controllerDescriptor;
if (_controllers.Value.TryGetValue(key, out controllerDescriptor))
{
return controllerDescriptor;
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
...
当我呼叫http://mysite.com/api/docs/“some-controller”时,SwaggerActionFilter没有收到我的请求。
如果我在没有版本控制的情况下在另一个解决方案中使用SwaggerUI,我就可以获得所有文档。
我知道也许我的版本选择器错了,但我不知道出了什么问题。