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

C# WebApi 接口测试工具:WebApiTestClient 应用详解

一、引言 由于最近项目需要开发 WebApi 接口,接口开发完了需要自测或提供给第三方进行调试,看了网上的方法,大多都是使用第三方测试工具,如 Postman、Fiddler 等,但这些虽然功能强大,但使用起来较为繁琐,如 Postman 还需要注册、下载及安装等,因此就搜索其他的调试方法,如 WebApiTestClient 和 swagger,这些都是轻量级的,可直接集成在项目中使用,很方便,…

云朵棉花糖发布于 2026/4/6更新于 2026/10/2166K 浏览
C# WebApi 接口测试工具:WebApiTestClient 应用详解

一、引言

由于最近项目需要开发 WebApi 接口,接口开发完了需要自测或提供给第三方进行调试,看了网上的方法,大多都是使用第三方测试工具,如 Postman、Fiddler 等,但这些虽然功能强大,但使用起来较为繁琐,如 Postman 还需要注册、下载及安装等,因此就搜索其他的调试方法,如 WebApiTestClient 和 swagger,这些都是轻量级的,可直接集成在项目中使用,很方便,本文主要介绍在 WebApi 中使用 WebApiTestClient 接口测试工具的应用。

二、WebApiTestClient 介绍

WebApiTestClient 是一款专门为调试和测试 ASP.NET WebApi 设计的工具,可以通过简洁的 Web 界面发送请求并查看响应。在 API 开发过程中,它可以帮助开发者更高效地进行调试和验证。

1、特性

  1. 简洁的 Web 界面:无需额外安装复杂的工具,通过 Web 浏览器即可访问和使用。
  2. 易于集成:作为 NuGet 包,可以方便地集成到现有的 ASP.NET WebApi 项目中。
  3. 灵活的请求配置:可以自定义 HTTP 方法、请求头、请求体等,便于模拟各种请求场景。
  4. 实时查看响应:即时查看 API 的响应,包括状态码、响应头和响应体,便于调试。

2、应用场景

1)开发阶段的调试

在开发阶段,WebApiTestClient 可以用于快速验证 API 是否按预期工作。通过其简洁的界面,可以轻松构造各种 HTTP 请求并查看响应,便于发现和修复问题。

2)测试 API 端点

在测试阶段,QA 工程师可以使用 WebApiTestClient 模拟各种请求,验证 API 的稳定性和正确性。能够自定义请求参数和请求体,也有助于进行边界测试和异常处理测试。

3)与前端开发的协同

前后端分离的开发模式下,前端开发人员可以使用 WebApiTestClient 测试后端 API 的接口,确保数据交互的正确性,减少前后端联调的时间和成本。

4)快速验证和演示

在需求评审或技术交流过程中,开发者可以使用 WebApiTestClient 进行快速验证和演示,展示 API 的功能和数据交互过程,提高沟通效率。

三、WebApiTestClient 具体使用

1、WebApi 项目引入组件

首先,我们需要定义一个 API 项目

文章配图

然后通过 Nuget 引入组件,如下图。记住选下图中的第一个 WebApiTestClient 进行安装。

文章配图

引入成功后,将向项目里面添加一些主要文件:

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

2、如何使用组件

目录

  1. 一、引言
  2. 二、WebApiTestClient 介绍
  3. 1、特性
  4. 2、应用场景
  5. 三、WebApiTestClient 具体使用
  6. 1、WebApi 项目引入组件
  7. 2、如何使用组件
  8. 1、修改 Api.cshtml 文件
  9. 2、配置读取注释的 xml 路径
  10. 3、测试接口
  11. 四、总结
1、修改 Api.cshtml 文件

通过上述步骤,就能将组件 WebApiTestClient 引入进来。下面我们只需要做一件事:打开文件 (根据 Areas\HelpPage\Views\Help) Api.cshtml 并添加以下内容:

  • @Html.DisplayForModel("TestClientDialogs")
  • @Html.DisplayForModel("TestClientReferences")

添加后 Api.cshtml 文件的代码如下

@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> @Html.DisplayForModel("TestClientDialogs") @section Scripts{ <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" /> @Html.DisplayForModel("TestClientReferences") }
2、配置读取注释的 xml 路径

其实,通过上面的步骤,我们的项目已经可以跑起来了,也可以调用接口测试。但是,还不能读取 ///

注释里面的东西。需要做如下配置才行。

(1)配置生成 xml 的路径。我们在项目上面点右键→属性→生成标签页配置 xml 的路径

文章配图

(2)在 xml 的读取路径:在下图的 HelpPageConfig.cs 里面配置一句话,指定 xml 的读取路径。

文章配图

这句代码如下:

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.SetSampleResponse(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> constructor
                    Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
                    object items = sampleGenerator.GetSampleObject(itemsType);
                    // Fill in the other information needed to invoke the PageResult<T> constructor
                    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
    }
}
3、测试接口

下面仅为简单接口,仅为项目说明使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApiDemo.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete()
        {
        }
    }
}

到这里组件就搭完了,剩下的就是运行了。如果我们是把 webAPI 部署在 IIS 或其他服务器上,在浏览器 url 里面敲地址 http://IP 地址:端口/Help 即可显示 WebApiTestClient 调试页面;这里我是直接通过 Visual Studio 2017 调试弹出 WebApiTestClient 调试页面,如下:

WebApiTestClient 调试页面展示:

文章配图

接口调试:

点击某一个接口查看接口详细。例如本文查看 Get 请求的无参方法,右下角有按钮可以测试接口。

文章配图

点击"Test API"按钮

文章配图

点击 Send 发送请求

文章配图

第二个有参数的接口

文章配图 文章配图

手动输入参数

文章配图

点"Send"得到返回结果

文章配图

四、总结

WebApiTestClient 是一种专门用于调试和测试 ASP.NET WebApi 的工具,其设计简洁、功能强大,具有以下几大优点:

  1. 简洁易用

    • Web 界面:无需安装繁琐的外部工具,通过浏览器即可访问和使用,界面友好,操作简单。
    • 易于集成:作为 NuGet 包,可以方便地集成到现有的 ASP.NET WebApi 项目中,配置简单,不需要额外的复杂步骤。
  2. 灵活的请求配置

    • 多种 HTTP 方法:支持 GET、POST、PUT、DELETE 等常见的 HTTP 请求方法,能够模拟各种请求场景。
    • 自定义请求参数:允许用户自定义请求头、请求体和查询参数,灵活性高,便于模拟实际应用中的复杂请求。
  3. 实时查看响应

    • 即时反馈:可以即时查看 API 的响应结果,包括状态码、响应头和响应体,帮助开发者快速发现和定位问题。
    • 详细信息:能够详细显示请求和响应的所有细节,便于调试和分析。
  4. 提高开发效率

    • 快速验证:在开发过程中,可以快速验证 API 的功能是否正确,无需切换到其他工具,大大提高开发效率。
    • 减少联调时间:前后端分离的开发模式下,前端开发人员可以快速验证后端 API 的接口,减少前后端联调的时间和成本。
  5. 便于展示和沟通

    • 演示友好:在需求评审或技术交流过程中,可以使用 WebApiTestClient 进行实时演示,展示 API 的功能和数据交互过程,提高沟通效率。
    • 文档生成:部分集成了 API 文档生成功能,便于开发者和测试人员查看和使用。
  6. 配置灵活

    • 路由配置:可以灵活配置路由,适应不同项目的需求。
    • 环境适应:适用于开发、测试环境,便于不同阶段的调试和测试工作。
  7. 无需依赖外部工具

    • 内置解决方案:作为 ASP.NET WebApi 的内置调试解决方案,不需要依赖外部工具,减少了环境配置和维护的复杂度。

WebApiTestClient 以其简洁易用、灵活配置、即时反馈等优点,成为了调试和测试 ASP.NET WebApi 的理想工具。它不仅提高了开发和测试效率,而且在前后端联调、需求评审等场景中也发挥了重要作用,为开发者提供了极大的便利。

更多推荐文章

查看全部
  • 基于 WebSocket 的外汇实时数据接入方案
  • AutoDL 服务器系统盘空间清理指南
  • 动态规划路径类 DP 入门:3 道经典例题解析
  • C++ 标准库:map 与 set 容器详解与实战
  • 4GB 显存限制下构建 LLM 基础开发环境指南
int id
Rokid 灵珠平台搭建旅游 AR 智能体实战指南
  • Harness Engineering:给 AI 套上缰绳的工程学
  • Flutter Web 跨域(CORS)本地调试方案
  • 《Agent Runtime 工程化》第六章 MCP 与 Provider 抽象:6.3 把 MCP 工具接入 Registry
  • 知网 AIGC 检测算法 3.0 升级要点与应对策略
  • Gemini AI 生成图片水印去除方法与技术解析
  • GitHub 全界面中文化:Tampermonkey 插件安装与配置指南
  • Python 基础入门:标识符、关键字与基本语句详解
  • Spring AI MCP Server 集成与示例
  • ARINC 825 协议核心面试百问
  • 未来 10 年值得关注的 5 个高薪行业
  • Linux 多路转接 IO 模型:select 详解
  • Python 结合 RAG 架构搭建本地智能问答机器人
  • Hadoop 运行模式及核心架构解析
  • 数据结构:栈与队列定义及 C 语言实现
  • 相关免费在线工具

    • curl 转代码

      解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online

    • 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