从 .NET 控制台调用 JSON WebService 的最佳方式 [英] Best way to call a JSON WebService from a .NET Console
问题描述
我在 ASP.Net MVC3 中托管一个 Web 服务,它返回一个 Json 字符串.从 c# 控制台应用程序调用 web 服务并将返回解析为 .NET 对象的最佳方法是什么?
I am hosting a web service in ASP.Net MVC3 which returns a Json string. What is the best way to call the webservice from a c# console application, and parse the return into a .NET object?
我应该在我的控制台应用程序中引用 MVC3 吗?
Should I reference MVC3 in my console app?
Json.Net 有一些很好的方法来序列化和反序列化 .NET 对象,但我没有看到它有从网络服务 POST 和 GET 值的方法.
Json.Net has some nice methods for serializing and deserializing .NET objects, but I don't see that it has ways for POSTing and GETing values from a webservice.
或者我应该创建自己的辅助方法来发布和获取网络服务?我如何将我的 .net 对象序列化为键值对?
Or should I just create my own helper method for POSTing and GETing to the web service? How would I serialize my .net object to key value pairs?
推荐答案
我使用 HttpWebRequest 从 Web 服务获取 GET,它返回一个 JSON 字符串.对于 GET,它看起来像这样:
I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:
// Returns JSON string
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
然后我使用 JSON.Net 来动态解析字符串.或者,您可以使用此 codeplex 工具从示例 JSON 输出静态生成 C# 类:http://jsonclassgenerator.codeplex.com/
I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/
POST 看起来像这样:
POST looks like this:
// POST a JSON string
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = @"application/json";
using (Stream dataStream = request.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
length = response.ContentLength;
}
}
catch (WebException ex) {
// Log exception and throw as for GET example above
}
}
我在我们的网络服务的自动化测试中使用这样的代码.
I use code like this in automated tests of our web service.
这篇关于从 .NET 控制台调用 JSON WebService 的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!