如何测试接收类的Web API发布方法 [英] How to test a web api post method which receives a class
问题描述
我创建了一个ASP.NET Web API,该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.
推荐答案
打开邮递员输入您要执行的操作的网址:
添加标头: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发布方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!