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

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

目录

一、引言      

二、WebApiTestClient介绍

1、特性

2、应用场景

三、WebApiTestClient具体使用

1、WebApi项目引入组件

2、如何使用组件

 1、修改Api.cshtml文件

2、配置读取注释的xml路径

3、测试接口

四、总结


一、引言      

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

二、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、修改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路径

其实,通过上面的步骤,我们的项目已经可以跑起来了,也可以调用接口测试。但是,还不能读取 /// <summary> 注释里面的东西。需要做如下配置才行。

(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> 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 } }

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(int id) { } } } 

         到这里组件就搭完了,剩下的就是运行了。如果过我们是是把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 的理想工具。它不仅提高了开发和测试效率,而且在前后端联调、需求评审等场景中也发挥了重要作用,为开发者提供了极大的便利。

Read more

从零开始:Xilinx FPGA实现RISC-V五级流水线CPU手把手教程

从一块FPGA开始,亲手造一颗CPU:RISC-V五级流水线实战全记录 你还记得第一次点亮LED时的兴奋吗?那种“我真正控制了硬件”的感觉,让人上瘾。但如果你能 自己设计一颗处理器 ,让它跑起第一条指令——那才是数字世界的终极浪漫。 今天,我们就来做这件“疯狂”的事:在一块Xilinx FPGA上,用Verilog从零实现一个 完整的RISC-V五级流水线CPU 。不是调用IP核,不是简化版demo,而是包含取指、译码、执行、访存、写回五大阶段,并解决真实数据冒险与控制冒险的可运行核心。 这不仅是一次教学实验,更是一场对计算机本质的深度探索。 为什么是 RISC-V + FPGA? 别误会,我们不是为了赶潮流才选RISC-V。恰恰相反,它是目前最适合学习CPU设计的指令集。 * 开放免费 :没有授权费,文档齐全,连寄存器编码都写得明明白白。 * 简洁清晰 :RV32I只有40多条指令,没有x86那样层层嵌套的历史包袱。 * 模块化扩展 :基础整数指令够用,后续想加浮点、压缩指令、向量扩展,都可以一步步来。

Cesium 无人机智能航线规划:航点动作组与AI识别实战

1. 从“点”到“任务”:理解智能航线规划的核心 如果你用过一些基础的无人机航线规划工具,可能觉得“不就是在地图上点几个点,连成线让飞机飞过去”吗?确实,早期的航点飞行就是这么简单。但当你真正投入到巡检、测绘、安防这类复杂任务时,你会发现,单纯的“点对点”飞行远远不够。 想象一下电力巡检的场景:无人机飞到第3号铁塔时,需要悬停、调整云台角度对准绝缘子串拍照;飞到第5号铁塔时,需要切换变焦镜头拍摄细节;在跨越河流的航线段,需要启动AI识别算法,自动监测河道漂浮物。这就不再是一条简单的“线”,而是一个由航点、动作、智能决策共同构成的三维空间任务流。 这就是Cesium在无人机应用开发中的独特价值。它不仅仅是一个三维地球可视化库,更是一个强大的空间任务编排平台。基于Cesium,我们可以将地理空间坐标(航点)与丰富的动作指令(Action) 以及AI识别逻辑绑定在一起,生成一个无人机能读懂、可执行的复杂任务剧本。 我刚开始做这类项目时,也走过弯路,以为把航线画漂亮就行了。结果真机测试时,要么动作没执行,

飞书机器人实战:5分钟搞定图片消息发送(含常见报错解决方案)

飞书机器人实战:5分钟搞定图片消息发送(含常见报错解决方案) 你是否遇到过这样的场景:服务器监控系统捕捉到一个异常峰值,你希望它能自动将一张清晰的图表截图,直接推送到团队的飞书群里,而不是一封冰冷的邮件;或者,你的自动化日报系统生成了精美的数据可视化图片,你希望它能无缝地出现在每日的晨会通知中。对于许多开发者和运维工程师来说,将图片消息集成到自动化流程中,是一个能极大提升信息传达效率和体验的“刚需”。 飞书机器人提供了强大的消息推送能力,但初次接触其图片消息发送功能时,你可能会发现它比预想的要“曲折”一些——它不像发送文本那样直接丢一个图片链接就行,而是需要经过一个“上传-获取密钥-发送”的流程。这个过程里,权限配置、tenant_access_token获取、图片上传格式、image_key的使用,每一步都可能藏着一个小坑。别担心,这篇文章就是为你准备的“避坑指南”。我们将抛开官方文档那略显冰冷的步骤罗列,从一个实战者的角度,带你用大约5分钟的时间,彻底打通从零到一发送飞书图片消息的全链路,并重点剖析那些你可能马上就会遇到的报错及其根因解决方案。我们的目标是:让你看完就能用,用了

深入解析OpenClaw Skills:从原理到实战,打造专属机器人技能

深入解析OpenClaw Skills:从原理到实战,打造专属机器人技能

一、OpenClaw Skills:机器人行为的“最小执行单元” 1.1 什么是OpenClaw Skills? OpenClaw是面向开源机械爪/小型机器人的控制框架(核心仓库:openclaw/openclaw),旨在降低机器人行为开发的门槛。而Skills(技能) 是OpenClaw框架中对机器人“单一可执行行为”的封装模块——它将机器人完成某一特定动作的逻辑(如“夹取物体”“释放物体”“移动到指定坐标”)抽象为独立、可复用、可组合的代码单元。 简单来说: * 粒度:一个Skill对应一个“原子行为”(如“单指闭合”)或“组合行为”(如“夹取→移动→释放”); * 特性:跨硬件兼容(适配不同型号机械爪)、可插拔(直接集成到OpenClaw主框架)、可扩展(支持自定义参数); * 核心价值:避免重复开发,让开发者聚焦“