如何通过控制台应用程序调用POST RESTFUL服务
我有一个静态服务(POST),该服务接受Json对象作为输入(Fiddler中的请求正文).现在,我想使用动态值(从文本文件中读取或硬编码的值)来使用Console Applciation中的服务.我将记录操作,例如对于此测试数据XXXXX,服务将返回值.
I have a rest ful service (POST) which accepts Json object as an input (Request body in Fiddler). Now I wanted to consume the service from Console Applciation with dynamic values (either read from text file or hardcoded values). I will log the actions like, for this test data XXXXX, the service returns values.
任何人都可以帮助我如何使这一过程自动化.我想从控制台应用程序中使用此服务.
Can any one help me how to automate this process. I wold like to comsume this service from Console application.
请注意,还输出JSON字符串.
Pls note Output also JSON string.
任何建议都会对我有帮助.
Any suggestion will be really helpful for me.
从 nuget 在您的控制台项目中
添加对System.Net.Http和System.Runtime.Serialization的引用
Add a reference to System.Net.Http and System.Runtime.Serialization
创建要发送和接收的数据的合同类(与Web服务中的合同类相同)
Create a contract class of the data you want to send and receive (the same as in your webservice)
[DataContract]
public class YourObject{
[DataMember]
public int Id {get; set;}
}
在您的控制台应用程序中,按如下所示调用网络服务:
In your console app call the webservice like this:
var client = new HttpClient();
var response = client.PostAsJsonAsync<YourObject>("http://yourserviceurl:port/controller", objectToPost).Result;
if(response.IsSuccessStatusCode){
Console.WriteLine(response);
}else{
Console.WriteLine(response.StatusCode);
}
有关webapi的更多信息此处和
More info about webapi here and here