我是使用 API 并使用 asp.net 从他们那里获得响应的新手,我正在我的 asp.net Web 应用程序中调用 API,如下所示:
public ActionResult MakeCall() {
CallTRunkAPIResponse response = GET("https://apibetaus.calltrunk.com/api/v2/GetAccountSummarySimple?access_token=mytokenkeyhere");
return Content("Make a call");
}
我创建了一个方法来获取响应,将响应传输为 json 格式,然后使用 javascript 序列化程序转换为我的对象类型,如下所示:
public CallTRunkAPIResponse GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Headers.Add("X-Client:" + "header info from api here");
request.Headers.Add("X-Authenticator-Session:" + "session key from api here");
request.Method = "GET";
request.ContentType = "application/json";
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
//return reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
CallTRunkAPIResponse myojb = (CallTRunkAPIResponse)js.Deserialize(objText, typeof(CallTRunkAPIResponse));
return myojb;
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
}
我的对象是这样的(不知道下面的响应我应该在这个响应类中有哪些属性:
public class CallTRunkAPIResponse {
public string Status { get; set; }
public string Content { get; set; }
public string Region { get; set; }
}
响应应该是这样的,但我收到错误:
{
"Status":"OK",
"Content":{
"Region":"beta.us",
"CurrencyCode":"USD",
"CurrencySymbol":"$",
"Languages":["en"],
"Version":{
"Api":{
"DisplayVersion":"2.0",
"Version":3},
"Client":{
"ReportedVersion":0,
"NewestVersion":2,
"MinVersion":2}
}
}
}
但我收到此错误:
System.ArgumentException: Invalid JSON primitive: .
在:
CallTRunkAPIResponse myojb = (CallTRunkAPIResponse)js.Deserialize(objText, typeof(CallTRunkAPIResponse));