Reputation: 1125
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; }
}
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.
Upvotes: 1
Views: 25079
Reputation: 3641
This is what I use to do: Use a REST client tester like Postman or Fiddler. I use Postman which is an app for Google Chrome.
For easy construction of JSON you can create a HttpGet method on you controller and return a fake constructed ImageData
and call it from Postman. Here you will see the JSON and use that for input to the POST method.
public class ImageSaveController : ApiController
{
public ImageData Get()
{
return new ImageData
{
// insert test data here
};
}
[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,"");
}
}
Upvotes: 2
Reputation: 1189
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 Web API 2 POST request simulation in POSTMAN Rest Client
If you want to make good tests, the better solution is to write unit tests.
Upvotes: 4