ASP.Net MVCWebApi下集成Swagger UI(.NetCore 和.NetFramework框架)

.NetFramework框架

1. 安装Swashbuckle v5.6.0 Nuget包(目前最新版)

在这里插入图片描述

2. 解决方案>属性>生成

在这里插入图片描述

3. 添加配置

引入Swashbuckle包,App_Start文件夹会自动添加 SwaggerConfig.cs 类,内部方式默认被注释掉了,取消 c.IncludeXmlComments(GetXmlCommentsPath());该句的注释,并在下方添加方法:

        private static string GetXmlCommentsPath()
        {
            return string.Format(@"{0}\bin\TransactionSearch.xml", AppDomain.CurrentDomain.BaseDirectory);
        }

在这里插入图片描述
在这里插入图片描述

4. 控制器内编写API接口

在这里插入图片描述

5. 浏览器执行

输入地址: http://xxxx/swagger
在这里插入图片描述

.NetCore框架

1. 引入 Swashbuckle 最新版本

在这里插入图片描述

2. 编写文档过滤器

继承 IDocumentFilter

public class TagDescriptionsDocumentFilter : IDocumentFilter
    {
        /// <summary>
        /// Apply
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="context"></param>
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Tags = new[] {
                new Tag{ Name = "PersonTransaction", Description = "个人交易" },
                new Tag{ Name = "GroupTransaction", Description = "机构交易" }
            };
        }
    }

3. Startup.cs类中注册

 public class Startup
    {
        private readonly IHostingEnvironment _hostingEnv;

        public Startup(IHostingEnvironment env, IConfiguration configuration)
        {
            _hostingEnv = env;
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = "xxxx接口",
                    Version = "v1",
                    Description = ""
                });

                // 注释
                c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml");

                // Tags描述
                c.DocumentFilter<TagDescriptionsDocumentFilter>();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/api/Home/Error");
            }

            app.UseSwagger(c =>
            {
                c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Host = httpReq.Host.Value);
            });

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "xxxx接口");
            });

            app.UseMvc();
        }
    }

4. 控制器下编写API接口

在这里插入图片描述
core版本的operationId属性设置:[SwaggerOperation(OperationId = "SelectPersonTransaction")]

5. 浏览器执行

执行地址: https://xxxx/swagger
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将Swagger整合到ASP.NET MVC项目中,可以按照以下步骤进行操作: 1. 安装Swagger NuGet包:在Visual Studio的NuGet包管理器控制台中,运行以下命令来安装Swagger和相关依赖: ``` Install-Package Swashbuckle ``` 2. 配置Swagger:在`Global.asax.cs`文件中的`Application_Start`方法中,添加以下代码来配置Swagger: ```csharp using System.Web.Http; using Swashbuckle.Application; protected void Application_Start() { // ... // 配置Swagger GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "My API"); // API版本和标题 c.IncludeXmlComments(GetXmlCommentsPath()); // 导入XML注释文件 }) .EnableSwaggerUi(); } private static string GetXmlCommentsPath() { return System.String.Format(@"{0}\bin\MyApi.XML", System.AppDomain.CurrentDomain.BaseDirectory); } ``` 3. 添加Swagger注释:在控制器的操作方法上,使用XML注释来描述API的摘要、请求和响应参数等信息。可以使用`///`注释格式或者通过XML文件导入注释。 ```csharp public class MyApiController : ApiController { /// <summary> /// 获取所有数据 /// </summary> /// <returns>数据列表</returns> [HttpGet] public IHttpActionResult Get() { // ... } } ``` 4. 运行项目:启动ASP.NET MVC项目,然后浏览器中访问`/swagger`路径,将会看到自动生成的Swagger UI界面,展示了API的文档和可以进行测试的功能。 通过以上步骤,就可以将Swagger整合到ASP.NET MVC项目中,使得开发人员和团队可以更方便地查看、测试和使用API

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值