Swagger-Net Shows controller name instead of endpoint method

淺唱寂寞╮ 提交于 2019-12-10 22:01:21

问题


I've been trying to figure out why Swagger-Net does not show the endpoint methods in a controller.

The C# project is using a Web API template based on .Net framework 4.6.1.

I get the same result when I use SwashBuckler, so it's not Swagger-Net that's the issue, but something that is not configured or missing.

The SwaggerConfig looks like this

    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("''");
                    });
    }
  }

I'm at a dead end at the moment since I have no idea why Swagger cannot read the methods action names.

The answer:

The WebApiConfig route is not by default configured to route with action

       config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

it has to be changed to

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );


回答1:


You need a route, not an actionname

[Route("SaveConsent")] 

Besides that, it is advisable to add expected responses like so:

[SwaggerResponse(HttpStatusCode.OK, "OK", typeof(User))] [SwaggerResponse(HttpStatusCode.BadRequest, "Error", typeof(string))] [SwaggerResponse(HttpStatusCode.NotFound, "Notfound", typeof(string))] 
[Route("SaveConsent")] 
[HttpPost] 



回答2:


Building on Leon's comment. You need to specify a Route as Leon showed above.

I'm not sure [ActionName()] is what you need at all since it will allow your API's consumer to specify the URI with characters .NET may not allow or using a different signature than your actual controller method.

See this post for the reason behind [ActionName()].



来源:https://stackoverflow.com/questions/47576436/swagger-net-shows-controller-name-instead-of-endpoint-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!