Harald S. Hanssen
Harald S. Hanssen

Reputation: 504

Swagger-Net Shows controller name instead of endpoint method

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

How it looks when Swagger references only the controller

The endpoint method looks like this

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 }
        );

With the {action} parameter added

Upvotes: 4

Views: 5801

Answers (2)

Leon
Leon

Reputation: 919

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] 

Upvotes: 1

&#196;lskar
&#196;lskar

Reputation: 2577

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()].

Upvotes: 2

Related Questions