asp.net mvc 集成swagger

在ASP.NET MVC项目中集成Swagger需要几个步骤:

  1. 通过NuGet安装Swashbuckle包。

  2. 在项目的App_Start文件夹中配置Swagger。

  3. 定义API的XML注释。

  4. 配置Swagger以使用这些注释。

以下是一个基本的配置示例:

首先,通过NuGet安装Swashbuckle包:

bash 复制代码
Install-Package Swashbuckle

然后,在App_Start文件夹中添加一个SwaggerConfig.cs文件,并配置Swagger:

cs 复制代码
using System.Web.Http;
using WebActivatorEx;
using Swashbuckle.Application;
 
[assembly: PreApplicationStartMethod(typeof(YourProject.SwaggerConfig), "Register")]
 
namespace YourProject
{
    public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;
 
            GlobalConfiguration.Configuration 
                .EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "My API");
                        
                        // 设置XML注释路径
                        var xmlFile = $"{typeof(SwaggerConfig).Assembly.GetName().Name}.xml";
                        var xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlFile);
                        c.IncludeXmlComments(xmlPath);
                    })
                .EnableSwaggerUi(c =>
                    {
                    });
        }
    }
}

确保项目属性中生成XML文档文件(通常在项目的Properties文件夹中的AssemblyInfo.cs文件中设置):

cs 复制代码
[assembly: XmlnsDefinition("http://schemas.datacontract.org/2004/07/YourProject.Models", "YourProject.Models")]
[assembly: Guid("YOUR-GUID-HERE")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("My ASP.NET MVC Project")]
[assembly: AssemblyProduct("MyProduct")]
[assembly: AssemblyTitle("MyProject")]
[assembly: AssemblyCompany("MyCompany")]
[assembly: AssemblyCopyright("Copyright © MyCompany 2023")]
[assembly: ComVisible(false)]

最后,在Global.asax.cs文件中添加以下代码以启用Swagger:

cs 复制代码
protected void Application_Start()
{
    // ...其他启动代码...
    SwaggerConfig.Register();
}

完成这些步骤后,运行项目并导航到/swagger路径(例如:http://localhost:port/swagger),你应该能够看到Swagger UI界面。

相关推荐
代龙涛1 天前
WordPress 主题初体验:从 style.css 到 index.php、single.php 简单实战
后端·php·wordpress
zzb15801 天前
RAG from Scratch-优化-query
java·数据库·人工智能·后端·spring·mybatis
必胜刻1 天前
RESTful 基础:资源、路径与方法对应关系详解
后端·restful
XPoet1 天前
AI 编程工程化:Hook——AI 每次操作前后的自动检查站
前端·后端·ai编程
J2虾虾1 天前
在SpringBoot中使用Druid
java·spring boot·后端·druid
程序员小假1 天前
为什么要有 time _wait 状态,服务端这个状态过多是什么原因?
java·后端
qwert10371 天前
跨域问题解释及前后端解决方案(SpringBoot)
spring boot·后端·okhttp
yuweiade1 天前
【Spring】Spring MVC案例
java·spring·mvc
90后的晨仔1 天前
OpenClaw Windows 完整安装指南
后端
IT_陈寒1 天前
Vue组件复用率提升300%?这5个高阶技巧让你的代码焕然一新!
前端·人工智能·后端