在C#可视化工作室的API自动化测试中,请求主体返回null



这是我的代码

public static RestRequest CreateReportRequest()
{            
restRequest = new RestRequest(Method.POST);
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddHeader("Authorization", "Basic T1NUAxNFVxeTIwag==");
using (StreamReader file = 
File.OpenText(@"C:AutomationAPIAutomationSuiteAPIAutomationSuiteTestDataCreateReport.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject Body = (JObject)JToken.ReadFrom(reader);                    
}            
restRequest.AddJsonBody(Body);
var response = client.Execute(restRequest);
return restRequest;
}

当我调试代码时,我在";JObject Body;但当按下F10并移动到下一个语句时(restRequest.AddJsonBody(Body(;(Body值变为null。这引发了一个错误的请求错误。请帮我做这个。

您的Body变量在using语句的内部范围内声明。因此,当您试图在using之外引用它时,它是未声明的。

您可以将方法的末尾完全移动到using范围中,我想这将消除您的问题。例如:

...
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject Body = (JObject)JToken.ReadFrom(reader);     
restRequest.AddJsonBody(Body);
var response = client.Execute(restRequest);
return restRequest;               
}            

了解范围

最新更新