简体   繁体   中英

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.

Swagger仅引用控制器时的外观

端点方法如下所示

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

添加了{action}参数

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

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] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM