我遇到了一些问题,希望有人遇到这个问题并知道发生了什么。
我正在调用我们的WebAPI来获取$resource
(angularJS控制器代码)
Controller.service.common.GetData.get({pubPolyData: objData}, function
(Response) {
// success
Do stuff...
}
(AngularJS服务)
GetData: $resource(myURL, {}),
通过类型为string的APIController(这是一个c#可继承对象)。
我正在使用System.Net.WebClient();
来调用response = client.DownloadString(theURI);
,其中response
是返回给AngularJS的内容。
这是在ApiController中返回的内容
{"ObjectName":[{"ID":"123456","FormalName":"LastName, FirstName","SearchName":null,"Number":"xx-123-456789","OfficeName":"Some Office INC","Code":"987654","CompanyCode":"852","StateAbbr":"MN"}]}
...但是你可以看到Controller.service.common.GetTheData.get({sendData: objData}, function (myResponse)
调用myResponse
的回复实际上是正确的数据,但是每个字符的数组都是分开的
Response [object (Resource)]
_proto_ [object (Resource)]
$promise [object (Promise)]
$resolved true
[0] "{"
[1] "\"
[2] "O"
[3] "b"
[4] "j"
[5] "e"
[0] "c"
[1] "t"
[2] "N"
[3] "a"
[4] "m"
[5] "e"
[0] ":"
[1] "["
[2] "{"
[3] "I"
[4] "D"
[5] ":"
...等
......我在这里错过了什么?
答案 0 :(得分:0)
因此,实际问题是在HttpResponseMessage(本地控制器)类型的控制器内部获取HttpResponseMessage(来自远程WebAPI)并尝试将其传递回$ resource ... no bueno!
我实际做的是将Local控制器更改为SimpleResponse ..." T"是你想要填充的模型。是的,不幸的是,如果您因为某种原因需要在此处调用您的遥控器,则必须在本地控制器上复制模型。
有了这个,我反序列化了Object并将SimpleResponse返回到$ resource,一切都很开心!!
public class MyControllerController : ApiController {
public SimpleResponse<DataModel> GET(string _inData) {
DataModel data = new DataModel();
try {
System.Net.WebClient client = new System.Net.WebClient();
String Domain = CallToGetValueFromWebConfig("WEBAPIURL", "value");
String theURI = String.Format("{0}api/ApIControllerName?_inData={1}", Domain, _inData);
client.BaseAddress = theURI;
client.UseDefaultCredentials = true;
var json = client.DownloadString(theURI);
data = JsonConvert.DeserializeObject<DataModel>(json, new JsonSerializerSettings() {
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
} catch (Exception ex) {
EventLogging.AddExceptionEvent(EventLogging.EventID.WebApiDataGet, "Some error text", ex);
}
return new SimpleResponse<DataModel> { Data = data};
}
}
}
答案 1 :(得分:-2)
您可以使用Newtonsoft库
string json = "{\"ObjectName\":[{\"ID\":\"123456\",\"FormalName\":\"LastName, FirstName\",\"SearchName\":null,\"Number\":\"xx-123-456789\",\"OfficeName\":\"Some Office INC\",\"Code\":\"987654\",\"CompanyCode\":\"852\",\"StateAbbr\":\"MN\"}]}";
var response = Newtonsoft.Json.Linq.JToken.Parse(json)["ObjectName"];
这将返回
[
{
"ID": "123456",
"FormalName": "LastName, FirstName",
"SearchName": null,
"Number": "xx-123-456789",
"OfficeName": "Some Office INC",
"Code": "987654",
"CompanyCode": "852",
"StateAbbr": "MN"
}
]