我将使用RestSharp测试REST API,并且需要post方法来发布数据并基于回调给出状态(错误,无效,成功),即发出INVALID,即“对象引用未设置为对象的实例”{{ 3}}
这是我的TestMethod
[TestMethod()]
public void AddNewBFormat()
{
Random r = new Random((int)DateTime.Now.Ticks);
var x = r.Next(100000, 999999);
string s = x.ToString("000000");
string UniqueFileName = "S" + s + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
request.Resource = "api/BFormat/AddNewBFormat";
request.Method = Method.POST;
var body= "{'UploadFileVM':{'BordereauxId':null,'BFormatId':null,'FileName':'"+UniqueFileName+ "','Filesize':0,'Path':'C:\\Applications\\new\\\\TempUploadedFiles','size':0,'ActiveSheetIndex':0,'HeaderIndex':0,'MultiHeaders':null,'SheetNames':null,'IsPasswordProtected':false},'BFormat':{'UniqueFileName':'"+ UniqueFileName+"'}}";
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-type", "application/json");
request.AddParameter("Application/Json", body, ParameterType.RequestBody);
var queryResult = client.Execute<ResponseData<Guid>> (request).Data;
try
{
Assert.IsTrue(queryResult.ReturnData != null);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
我已尝试过request.addJsonBody
,但我想知道使用POST方法发送json数据的相同结果
答案 0 :(得分:0)
在您的web api中,您需要处理绑定的json数据。 WebApi通常会自行完成。
而且你也不必用&#34; application / json&#34;添加标题或任何参数。
如果您只需使用AddJsonBody(object obj)
方法,RestSharp将自动设置标题。
或者另一种方法是:
Random r = new Random((int)DateTime.Now.Ticks);
var x = r.Next(100000, 999999);
string s = x.ToString("000000");
string UniqueFileName = "S" + s + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
request.Resource = "api/BFormat/AddNewBFormat";
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json;
var body = new
{
UploadFileVM = new
{
BordereauxId = "",
BFormatId = "",
FileName = UniqueFileName,
Filesize = 0,
Path = @"c:\sdakdldas\"
}
};
request.AddBody(body); //enter code herE
var queryResult = client.Execute<ResponseData<Guid>>(request).Data;
try
{
Assert.IsTrue(queryResult.ReturnData != null);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
不要自己序列化数据。 RestSharp将负责序列化。