如何在swagger-ui中更改控制器的名称? [英] How to change controller's name in swagger-ui?

查看:380
本文介绍了如何在swagger-ui中更改控制器的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有以下条件:

MySimpleTestController : ApiController
{
}

是否可以在生成的API文档中将控制器名称显示为我的简单测试"而不是"MySimpleTest"?

Is it possible to have the controller name appear as "My Simple Test" instead of "MySimpleTest" in the generated API docs?

我进行了搜索,但是我主要找到了使用@Api注释在Java中进行搜索的方法,但我使用的是C#(.net 4.5.2).

I did a search but I mostly found ways to do it in Java using an @Api annotation but I am using C# (.net 4.5.2).

这是一个的方法,但是它需要在Controller中的每条路由上添加注释,这会很麻烦,因为我的控制器有很多路由.有更好的方法吗?

Here is one way to do it but it requires adding an annotation to every single route in the Controller which would be cumbersome as my controller has many routes. Is there a better way?

推荐答案

这就是我最终要做的事情:

Here's how I ended up doing it:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class SwaggerControllerNameAttribute : Attribute
{
    public string ControllerName { get; private set; }

    public SwaggerControllerNameAttribute(string ctrlrName)
    {
        if (string.IsNullOrEmpty(ctrlrName))
        {
            throw new ArgumentNullException("ctrlrName");
        }
        ControllerName = ctrlrName;
    }
}

然后将以下代码添加到配置中:

And then add the following code to the configuration:

configuration.EnableSwagger(c =>
{
     c.GroupActionsBy(apiDesc =>
     {
          var attribute = apiDesc.GetControllerAndActionAttributes<SwaggerControllerNameAttribute>();
          if (attribute.Any())
          {
               return attribute.First().ControllerName;
          }
          else
          {
               return apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName;
          }
     });        
}

然后您可以执行以下操作:

And then you can do this:

[SwaggerControllerName("My Simple Test")]
public class MySimpleTestController : ApiController
{
}

这篇关于如何在swagger-ui中更改控制器的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆