我正在尝试在我的ASP. Net
应用中调用WebService并收到以下错误:Error: Unexpected token '<'
。到目前为止,这似乎是json
的解析问题,但我不确定如何解决。在我的应用程序中,我有一个数据管理器,该数据管理器从本地SQL .mdf
数据库中调用存储过程。本质上,它是一个名为GetEventsByState()的公共DataTable
,它存储在我的DataAcessManager.cs
文件中。从我的App_Service.asmx.cs文件中的WebService调用它。目标是在datatable
中将WebService
作为json返回,以便随后可以在我的app.js
文件中调用它:
RII_Service.cs
[WebMethod]
public string GetListOfEventsByState()
{
_dtMgr = new DataAccessManager();
//string state = st;
/*HttpContext.Current.Response.Write(GetEventsData());*/
DataTable EventsList = _dtMgr.GetEventsByState();
var lst = EventsList.AsEnumerable()
.Select(r => r.Table.Columns.Cast<DataColumn>()
.Select(c => new KeyValuePair<string, object>(c.ColumnName, r[c.Ordinal])
).ToDictionary(z => z.Key, z => z.Value)
).ToList();
//now serialize it
try
{
string json = new JavaScriptSerializer().Serialize(lst);
json = json.TrimEnd();
return json;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
然后在页面加载时在WebMethod
中调用此app.js
,如下所示:
app.js
//Function to call Asp.Net Web Service and retrieve events list by state
var EventsData = esriRequest({
url: "RII_Service.asmx/GetListOfEventsByState",
content: {
},
dataType: "jsonp",
handleAs: "json"
});
EventsData.then(
function (response) {
console.log(response);
events_json = response;
....
}, function (error) {
console.log("Error: ", error.message);
});
当我在RII_Service.cs上为WebMethod
GetListOfEventsByState()设置断点时,它会生成一个可行的json字符串,如下所示:
"[{\"FullEventName\":\"NJ Cindy 2005\",\"State\":\"NJ\"},{\"FullEventName\":\"NJ Gordon 2000\",\"State\":\"NJ\"}...]
但是,当它返回到EventsData
请求时,它会直接返回错误。关于我在这里做错什么的任何线索或建议。
答案 0 :(得分:1)
在RII_Service.cs中调用WebMethod时,似乎将xml / html拖到app.js
请求中。尽管GetListOfEventsByState()
显示返回了json string
,但<string>
标记总是会在app.js
端被拾取(从而解释了'<'
错误)。为了解决这个问题,我做了两件事。首先,使用NewtonSoft.Json
方法JsonConvert
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
*您可能必须先使用“工具”>“ NuGet软件包”进行安装。然后,我使用System.Web.HttpContext
格式化输出。因此,我按如下方式重新编写了WebMethod GetListOfEventsByState()
并成功了。希望这对遇到类似问题的人有所帮助:
[WebMethod]
//public string GetListOfEventsByState()
public void GetListOfEventsByState()
{
_dtMgr = new DataAccessManager();
DataTable EventsList = _dtMgr.GetEventsByState();
//now serialize it
try
{
string JSONresult;
JSONresult = JsonConvert.SerializeObject(EventsList);
HttpContext.Current.Response.Write(JSONresult);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}