像asp.net core webapi一样在asp.net frameworks中使用Swagger,方便调试接口

用asp.net core 开发webapi,默认在开发环境有一个Swagger页面,可以让开发者直接在浏览器下测试接口,而我们早在.net framewokrs时,用一般处理程序来充当接口,现在我们也让他在开发环境有一个Swagger页面,如此就能像在core框架下方便调试接口了。为最简单地说明问题,我们代码尽量简化。

第一步,建立一个空的asp.net frameworks空网站,添加一个一般处理程序,此处取名为DemoHandler.ashx,"随便"编写一些简单代码,比如

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SwaggerForAshx
{
    /// <summary>
    /// DemoHandler 的摘要说明
    /// </summary>
    public class DemoHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            // 设置响应格式为纯文本
            context.Response.ContentType = "text/plain";

            // 区分 GET/POST 请求
            if (context.Request.HttpMethod.Equals("GET", System.StringComparison.OrdinalIgnoreCase))
            {
                // GET 请求:默认输出 Hello World
                context.Response.Write("Hello World");
            }
            else if (context.Request.HttpMethod.Equals("POST", System.StringComparison.OrdinalIgnoreCase))
            {
                // POST 请求:接收 name 参数,输出 你好,XX
                string userName = context.Request.Form["name"] ?? "";

                if (!string.IsNullOrEmpty(userName))
                {
                    context.Response.Write($"你好,{userName}");
                }
                else
                {
                    context.Response.StatusCode = 405;
                    context.Response.Write("缺少参数");
                }
               
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

第二步,然后通过nuget下载安装Swashbuckle,安装完成后我们看到,项目中多了一个Swashbuckle.cs的配置文件(未修改前代码略),修改Swashbuckle,代码如下

csharp 复制代码
using SwaggerForAshx;
using Swashbuckle.Application;
using Swashbuckle.Swagger;
using System.Collections.Generic;
using System.Linq;
using System.Web.Configuration;
using System.Web.Http;
using WebActivatorEx;

[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

namespace SwaggerForAshx
{
    public class SwaggerConfig
    {

        public static void Register()
        {
            bool isDebuggingEnabled = WebConfigurationManager
            .GetWebApplicationSection("system.web/compilation") // 定位到compilation节点
            is CompilationSection compilationSection
            && compilationSection.Debug; // 读取Debug属性(true/false)
            //--
            if (isDebuggingEnabled) //仅在开发环境下才能使用Swagger
            {
                GlobalConfiguration.Configuration
               .EnableSwagger(c =>
               {
                   c.SingleApiVersion("v1", "ASHX 调用测试");
                   c.ResolveConflictingActions(api => api.First());

                   // 核心:5.6.0 专属------自定义文档提供器,手动添加 ashx 接口
                   c.CustomProvider((defaultProvider) =>
                       new CustomSwaggerProvider(defaultProvider));
               })
               .EnableSwaggerUi(c =>
               {
                   c.DocumentTitle("ASHX 调用测试专用页面");
               });
            }
           
        }

        public class CustomSwaggerProvider : ISwaggerProvider
        {
            private readonly ISwaggerProvider _defaultProvider;

            public CustomSwaggerProvider(ISwaggerProvider defaultProvider)
            {
                _defaultProvider = defaultProvider;
            }

            // 重写 GetSwagger 方法,手动添加 ashx 接口
            public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
            {
                // 获取默认 Swagger 文档
                var swaggerDoc = _defaultProvider.GetSwagger(rootUrl, apiVersion);


                swaggerDoc.paths["/DemoHandler.ashx"] = new PathItem
                {
                    // 指定 HTTP 方法为 GET
                    get = new Operation
                    {
                        tags = new List<string> { "测试接口" }, // 接口分类
                        summary = "默认get输出", // 接口说明
                        responses = new Dictionary<string, Response>
                        {
                            // 响应状态码和说明
                            ["200"] = new Response { description = "返回 Hello World 字符串" }
                        }
                    },
                    post = new Operation
                    {
                        tags = new List<string> { "测试接口" },
                        summary = "输出 你好,XX(POST)",
                        // 声明 POST 参数(表单方式传参,适配 Swagger 测试)
                        parameters = new List<Parameter>
        {
            new Parameter
            {
                name = "name", // 参数名
                @in = "formData", // 参数位置:表单(Swagger 里能直接输入)
                description = "要问候的用户名",
                required = true, // 必传
                type = "string" // 参数类型
            }
        },
                        responses = new Dictionary<string, Response>
                        {
                            ["200"] = new Response { description = "返回 你好,XX" },
                            ["400"] = new Response { description = "参数缺失或错误" },
                            ["405"] = new Response { description = "仅支持 GET 请求" },
                            ["500"] = new Response { description = "服务器内部错误" }
                        }
                    }
                };

                //---

                return swaggerDoc;
            }
        }
    }
}

代码完成,启动调试运行,在地址栏域名后加上swagger,比如https://localhost:[你的端口号]/swagger。完工

相关推荐
2401_895521345 小时前
SpringBoot Maven快速上手
spring boot·后端·maven
disgare6 小时前
关于 spring 工程中添加 traceID 实践
java·后端·spring
ictI CABL6 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
小江的记录本8 小时前
【Linux】《Linux常用命令汇总表》
linux·运维·服务器·前端·windows·后端·macos
yhole11 小时前
springboot三层架构详细讲解
spring boot·后端·架构
香香甜甜的辣椒炒肉11 小时前
Spring(1)基本概念+开发的基本步骤
java·后端·spring
白毛大侠12 小时前
Go Goroutine 与用户态是进程级
开发语言·后端·golang
ForteScarlet12 小时前
从 Kotlin 编译器 API 的变化开始: 2.3.20
android·开发语言·后端·ios·开源·kotlin
大阿明12 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端
Binary-Jeff12 小时前
Spring 创建 Bean 的关键流程
java·开发语言·前端·spring boot·后端·spring·学习方法