跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
C#

为 ASP.NET WebApi 嵌入内建调试页面:WebApiTestClient 配置过程

在 ASP.NET WebApi 项目里集成 WebApiTestClient,可以把接口测试页面直接嵌进去,省去外部工具切换的麻烦。配置分三步:通过 NuGet 安装包,在 Help 页面视图末尾渲染测试对话框和引用模板,最后开启 XML 文档生成并在 HelpPageConfig 中指定注释文件路径。启动后访问 /Help 就能看到每个接口的 Test API 按钮,输入参数即可查看实时响应。整个过程零依赖,对开发阶段快速验证和前后端联调挺有用。

Pythonist发布于 2026/6/17更新于 2026/10/766 浏览
为 ASP.NET WebApi 嵌入内建调试页面:WebApiTestClient 配置过程

在开发 ASP.NET WebApi 时,经常需要自测接口或供前端临时调试。Postman、Fiddler 固然强大,但来回切换环境、拼装请求也挺烦的。WebApiTestClient 这个 NuGet 包可以直接把测试页面嵌入项目,通过浏览器就能调,不用额外安装任何东西。

它的好处总结下来就几点:零依赖集成在项目里;支持自定义 HTTP 方法、请求头和请求体;响应状态码、响应头、响应体即时显示;前端同学也能直接打开 Help Page 去调接口,联调成本低一些。

不过要让它工作,配置过程有几个坑点,这里记录一下。

1. 安装包

在 VS 里打开 WebApi 项目,NuGet 搜索 WebApiTestClient 安装就行。装完之后,项目里会多出这几个文件:

  • Scripts\WebApiTestClient.js
  • Areas\HelpPage\TestClient.css
  • Areas\HelpPage\Views\Help\DisplayTemplates\TestClientDialogs.cshtml
  • Areas\HelpPage\Views\Help\DisplayTemplates\TestClientReferences.cshtml

2. 修改帮助页面视图

找到 Areas\HelpPage\Views\Help\Api.cshtml,在末尾把测试对话框和引用模板渲染出来。我的做法是在原有内容下面加上:

@Html.DisplayForModel("TestClientDialogs")
@section Scripts{
    <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
    @Html.DisplayForModel("TestClientReferences")
}

如果你项目里的 Api.cshtml 本身就有 @section Scripts 块,直接把这两行合并进去就行。

原来的文件大概长这样(不同模板可能有差别):

@using System.Web.Http 
@using WebApiDemo.Areas.HelpPage.Models 
@model HelpPageApiModel 
@{ var description = Model.ApiDescription; ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath; } 
<link type="text/css" href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" /> 
<div> 
<section> 
<div> <p> @Html.ActionLink("Help Page Home", "Index") </p> </div> </section> 
<section> @Html.DisplayForModel() </section> </div> 

加上测试相关部分后,页面底部就会多出测试按钮。

3. 配好 XML 文档注释

想让接口列表自动显示你在代码里写的 /// <summary> 注释,需要把 XML 文档生成打开。右键项目 → 属性 → 生成 → 勾选'XML 文档文件',路径默认是 App_Data\项目名.xml。

然后打开 Areas/HelpPage/HelpPageConfig.cs,在 Register 方法里把那个被注释掉的 SetDocumentationProvider 打开,并把路径改成你自己的:

config.SetDocumentationProvider(
    new XmlDocumentationProvider(
        HttpContext.Current.Server.MapPath("~/App_Data/WebApiDemo.xml")
    )
);

原文件里有很多注释,大部分是示例,不动也没事。关键是确保上面这行是生效的。完整的 HelpPageConfig.cs 可以参考:


// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData // package to your project. ////#define Handle_PageResultOfT using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Web; using System.Web.Http; #if Handle_PageResultOfT using System.Web.Http.OData; #endif namespace WebApiDemo.Areas.HelpPage { /// <summary> /// Use this class to customize the Help Page. /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation /// or you can provide the samples for the requests/responses. /// </summary> public static class HelpPageConfig { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "WebApiDemo.Areas.HelpPage.TextSample.#ctor(System.String)", Justification = "End users may choose to merge this string with existing localized resources.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "bsonspec", Justification = "Part of a URI.")] public static void Register(HttpConfiguration config) { //// Uncomment the following to use the documentation from XML documentation file. //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type //// formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> //{ // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} //}); // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if Handle_PageResultOfT config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. config.SetSampleForMediaType( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new MediaTypeHeaderValue("application/bson")); //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" //// and action named "Put". //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" //// on the controller named "Values" and action named "Get" with parameter "id". //config.SetResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.SetActualRequestType(typeof(string), "Values", "Get"); //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.SetActualResponseType(typeof(string), "Values", "Post"); config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/WebApiDemo.xml"))); } #if Handle_PageResultOfT private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) { if (type.IsGenericType) { Type openGenericType = type.GetGenericTypeDefinition(); if (openGenericType == typeof(PageResult<>)) { // Get the T in PageResult<T> Type[] typeParameters = type.GetGenericArguments(); Debug.Assert(typeParameters.Length == 1); // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor Type itemsType = typeof(List<>).MakeGenericType(typeParameters); object items = sampleGenerator.GetSampleObject(itemsType); // Fill in the other information needed to invoke the PageResult<T> constuctor Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor ConstructorInfo constructor = type.GetConstructor(parameterTypes); return constructor.Invoke(parameters); } } return null; } #endif } }

4. 跑起来看看

配置完成后启动项目。如果部署在 IIS 上,访问 http://IP:端口/Help;本地调试就直接看浏览器弹出的页面。

WebApiTestClient 调试页面

点任意接口进去,比如一个无参 GET,右下角就会出现 Test API 按钮。

接口调试入口

点击按钮会展开参数输入区。

点击 Test API

对于带参接口,填完参数后点 Send。

手动输入参数

下面会立刻返回状态码、响应头和响应体。

获取返回结果

整个过程基本没有脱离 IDE 或浏览器的感觉,很适合开发中快速验证。

小结

WebApiTestClient 算不上高级货,但在 ASP.NET WebApi 项目里省时间是真的。不用切出去开 Postman,改完代码随手点两下就能看结果。加上 XML 注释自动生成接口说明,对维护协作也有点帮助。唯一难受的是那个默认的 HelpPageConfig.cs 里面一堆注释,容易眼花,建议用的时候直接找 SetDocumentationProvider 那行改掉就好。

目录

  1. 1. 安装包
  2. 2. 修改帮助页面视图
  3. 3. 配好 XML 文档注释
  4. 4. 跑起来看看
  5. 小结

更多推荐文章

查看全部
  • FastJson2 完整使用指南(Java 后端企业级实战)
  • 基于 Z-Image-Turbo 的本地 AI 绘画部署:16GB 显存支持与双语提示
  • 本地部署 Stable Diffusion 3.5 完整教程
  • Claude Skills 与 MCP 对比:为何 Skills 更省 Token 且易用
  • NVIDIA RTX PC 开源 AI 工具升级:LLM 与扩散模型性能优化
  • Python Flask 框架与 Jinja2 模板引擎配置使用指南
  • 算法模拟法解题实战
  • 基于 Renderless 架构实现 DialogBox 可缩放功能及 WebAgent 实践
  • GitHub 文件夹精准下载指南:三步获取所需文件
  • 低空经济新实践:无人机如何革新光伏电站巡检
  • 机器人未知测量噪声的扩展卡尔曼滤波同时定位与地图绘制
  • 深入理解 Web Worker:Web 前端多线程实战
  • Spring AI 框架入门与应用指南
  • C++内存模型与原子操作
  • Stable Diffusion 本地部署与 WebUI 安装详解
  • AI 时代:赋能未来还是颠覆性科技革命?
  • AD9361 FPGA 纯 Verilog 驱动:LVDS 接口无依赖库
  • LeetCode 原地复写零:双指针与逆向填充的 O(n) 解法
  • Python 实现 PAT 乙级 1021 个位数统计
  • AR 眼镜移动端应用软件概述与技术展望

相关免费在线工具

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online

  • JSON 压缩

    通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online

  • JSON美化和格式化

    将JSON字符串修饰为友好的可读格式。 在线工具,JSON美化和格式化在线工具,online