一般经常写WEBAPI,推送给别人可以用postapi来测试,但是如果自己写webapi,对方还没有接口,怎么保证自己写的推送接口是正确的呢,这时候就可以使用以下方法

核心方法如下


/// <summary> /// 抓取推送到指定端口的webapi post请求 /// </summary> private static void CreateStubRequestBodyMatching() { server.Given( // 设置模拟的POST请求响应 Request.Create() .UsingPost() .WithPath("/saveSwdTempHumidityAlarms")  //这里模拟的对方接收推送的api方法为saveSwdTempHumidityAlarms ) .RespondWith( Response.Create() .WithStatusCode(200) // This extracts the book.title element from the JSON request body // (using a JsonPath expression) and repeats it in the response body .WithBody(request => { Console.WriteLine(string.Format("IP:{0}发起API推送,调用结果:", request.ClientIP)); Console.WriteLine(request.Body); Console.WriteLine(); return request.Body; }) // 原样返回请求体 .WithHeader("Content-Type", "application/json") // 设置响应头为 JSON ); ); }

调用方法

static void Main(string[] args)
{
    Test();
}
private static void Test()
{
    try
    {
        Console.WriteLine("请输入需要监听的端口号:");
        var port = Console.ReadLine();
        if (int.Parse(port) > 0)
        {
            Console.WriteLine("服务器监听中...");
            server = WireMockServer.Start(int.Parse(port));
            CreateStubRequestBodyMatching();
            Console.ReadKey();
        }
    }
    catch
    {
        Console.WriteLine("输入有误请重新输入:");
        Test();
    }
}

我方推送调用方式(post)可以直接使用postman推送:

//注意这里的saveSwdTempHumidityAlarms 是对应上面固定的监听方法对象
http://192.168.1.14:8199/saveSwdTempHumidityAlarms 

 

image

 

posted on 2025-12-02 16:51  JerryBolgs  阅读(0)  评论(0)    收藏  举报