Swagger-Net 显示控制器名称而不是端点方法
Swagger-Net Shows controller name instead of endpoint method
我一直在试图弄清楚为什么 Swagger-Net 没有在控制器中显示端点方法。
C# 项目正在使用基于 .Net framework 4.6.1 的 Web API 模板。
我在使用 SwashBuckler 时得到了相同的结果,所以这不是 Swagger-Net 的问题,而是未配置或缺失的问题。
SwaggerConfig 看起来像这样
public class SwaggerConfig
{
/// <summary>
///
/// </summary>
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", nameof(ConsentResponseApp));
c.AccessControlAllowOrigin("*");
c.IncludeAllXmlComments(thisAssembly, AppDomain.CurrentDomain.BaseDirectory);
})
.EnableSwaggerUi(c =>
{
c.UImaxDisplayedTags(100);
c.UIfilter("''");
});
}
}
我现在陷入了死胡同,因为我不知道为什么 Swagger 无法读取方法操作名称。
答案:
默认情况下,WebApiConfig 路由未配置为带有操作的路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
必须改为
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
基于 Leon 的评论。您需要指定一条路线,如 Leon 上面所示。
我不确定 [ActionName()]
是否是您所需要的,因为它将允许您的 API 的消费者指定带有字符的 URI。NET 可能不允许或使用不同的签名比你实际的控制器方法。
参见 this post 了解 [ActionName()]
背后的原因。
您需要路线,而不是动作名称
[Route("SaveConsent")]
除此之外,建议添加如下预期响应:
[SwaggerResponse(HttpStatusCode.OK, "OK", typeof(User))] [SwaggerResponse(HttpStatusCode.BadRequest, "Error", typeof(string))] [SwaggerResponse(HttpStatusCode.NotFound, "Notfound", typeof(string))]
[Route("SaveConsent")]
[HttpPost]
我一直在试图弄清楚为什么 Swagger-Net 没有在控制器中显示端点方法。
C# 项目正在使用基于 .Net framework 4.6.1 的 Web API 模板。
我在使用 SwashBuckler 时得到了相同的结果,所以这不是 Swagger-Net 的问题,而是未配置或缺失的问题。
SwaggerConfig 看起来像这样
public class SwaggerConfig
{
/// <summary>
///
/// </summary>
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", nameof(ConsentResponseApp));
c.AccessControlAllowOrigin("*");
c.IncludeAllXmlComments(thisAssembly, AppDomain.CurrentDomain.BaseDirectory);
})
.EnableSwaggerUi(c =>
{
c.UImaxDisplayedTags(100);
c.UIfilter("''");
});
}
}
我现在陷入了死胡同,因为我不知道为什么 Swagger 无法读取方法操作名称。
答案:
默认情况下,WebApiConfig 路由未配置为带有操作的路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
必须改为
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
基于 Leon 的评论。您需要指定一条路线,如 Leon 上面所示。
我不确定 [ActionName()]
是否是您所需要的,因为它将允许您的 API 的消费者指定带有字符的 URI。NET 可能不允许或使用不同的签名比你实际的控制器方法。
参见 this post 了解 [ActionName()]
背后的原因。
您需要路线,而不是动作名称
[Route("SaveConsent")]
除此之外,建议添加如下预期响应:
[SwaggerResponse(HttpStatusCode.OK, "OK", typeof(User))] [SwaggerResponse(HttpStatusCode.BadRequest, "Error", typeof(string))] [SwaggerResponse(HttpStatusCode.NotFound, "Notfound", typeof(string))]
[Route("SaveConsent")]
[HttpPost]