How to test a web api post method which receives a class(如何测试接收类的 web api post 方法)
问题描述
我创建了一个 ASP.NET Web API,它有一个名为 ImageSaveController
的控制器.这有一个 InsertImage
方法,可以将数据插入数据库,并且是一个 HttpPost
方法.此方法接收 ImageData
类型的对象作为参数.控制器代码和参数类如下:
I have created an ASP.NET web API which has a controller named ImageSaveController
. This has an InsertImage
method which inserts data into database and is an HttpPost
method. This method receives an object of type ImageData
as a parameter. The code for the controller and the parameter class are given below:
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 应用对其进行测试.
I would like to test it from a client. As you can notice, the ImageValue
property of the ImageData
class is a byte
array. Not sure how to pass the C# class parameter to this method. Ideally I would like to pass the parameter as json
and I am not sure how to construct the json
for this purpose. I am also not sure whether it could be tested using the chrome app called postman.
推荐答案
打开 postman 输入你的 url 到 action:
添加标题:Content-Type - application/json.
在正文选项卡中检查原始"(JSON)并输入您的数据.
Open postman enter your url to the action:
Add header: Content-Type - application/json.
In body tab check "raw" (JSON) and type your data.
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]
}
source POSTMAN中的Web API 2 POST请求模拟休息客户端
如果你想做出好的测试,更好的解决方案是编写单元测试.
If you want to make good tests, the better solution is to write unit tests.
这篇关于如何测试接收类的 web api post 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何测试接收类的 web api post 方法


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01