用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。完工