Skip to main content
 首页 » 编程设计

c#之如何测试接收类的 web api post 方法

2024年02月05日30freeliver54

我创建了一个 ASP.NET Web API,它有一个名为 ImageSaveController 的 Controller 。它有一个 InsertImage 方法将数据插入数据库,并且是一个 HttpPost 方法。此方法接收类型为 ImageData 的对象作为参数。 Controller 和参数类的代码如下:

public class ImageSaveController : ApiController 
{ 
    [HttpPost] 
    public IHttpActionResult InsertImage(ImageData imageData) 
    { 
        System.Data.SqlClient.SqlConnection conn = null; 
        try 
        {                
            //Image save to database code here 
        } 
        catch (Exception ex) 
        { 
            return Content(HttpStatusCode.NotModified, ex.Message); 
        } 
        finally 
        { 
            if (conn != null) 
                conn.Close(); 
        } 
        return Content(HttpStatusCode.OK,"");  
    } 
} 
 
//ImageData class 
public class ImageData 
{ 
    public int Id { get; set; } 
    public byte[] ImageValue { get; set; } 
} 

我想从客户端测试它。正如您所注意到的,ImageData 类的 ImageValue 属性是一个 byte 数组。不确定如何将 C# 类参数传递给此方法。理想情况下,我想将参数作为 json 传递,但我不确定如何为此构建 json 。我也不确定是否可以使用名为 postman 的 chrome 应用程序对其进行测试。

请您参考如下方法:

打开 postman 输入您的操作网址:
添加 header :Content-Type - application/json。
在正文选项卡中选中“原始”(JSON) 并输入您的数据。

POST /api/ImageSave/InsertImage/ HTTP/1.1 
Host: localhost:32378 
Content-Type: application/json 
Cache-Control: no-cache 
{ 
    "id" : 1, 
    "imageValue" : [11,141,123,121] 
} 

来源Web API 2 POST request simulation in POSTMAN Rest Client

如果你想做出好的测试,更好的解决方案是编写单元测试。