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

How to test a web api post method which receives a class(如何测试接收类的 web api post 方法)

本文介绍了如何测试接收类的 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 方法

基础教程推荐