我正在嘗試使用名爲FatSecret Sharp的包裝器調用Fatsecret API的基本ASP.NET應用程序,但是當出現此錯誤時我嘗試從我的JS腳本進行服務器端方法調用,並且想確定如何成功使用此包裝器創建Web應用程序。當調用FatSecret Sharp API時此時無法啓動異步操作
你會注意到來自包裝器的API調用明確提到它是「同步的」,所以我認爲這就是拋出錯誤,我只是不知道爲什麼,或者我怎樣才能成功地使用該調用一個Web應用程序。
這裏是我的代碼:
的Javascript
var jsonData;
function search() {
var element = document.getElementById("searchField")
var searchTerm = element.value;
callAJAX("FoodSearchExample", searchTerm);
}
function callAJAX(requestMethod, term) {
var pageMethod = "default.aspx/" + requestMethod;
$.ajax({
url: pageMethod,
data: JSON.stringify({ searchTerm : term }),
type: "POST",
contentType: "application/json",
dataType: "JSON",
timeout: 600000,
success: function (result) {
ajaxCallback(result.d);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
return false;
}
function ajaxCallback(serverResponse) {
if (serverResponse !== "loadLocations") {
//jsonData = JSON.parse(serverResponse);
alert(serverResponse);
}
else
alert("error");
}
C#
namespace HELP_Testing
{
public partial class _default : System.Web.UI.Page
{
private static string consumerKey = "key (removed from question)";
private static string consumerSecret = "secret (removed from question)";
[WebMethod]
public static string FoodSearchExample(string searchTerm)
{
FoodSearch foodSearch = new FoodSearch(consumerKey, consumerSecret);
string str = "";
var response = foodSearch.GetResponseSynchronously(new FoodSearchRequest()
{
SearchExpression = searchTerm
});
List<Food> foods = new List<Food>();
if (response.HasResults)
{
Food f;
foreach (var food in response.foods.food)
{
f = new Food();
f.FoodId = food.food_id;
f.FoodType = food.food_type;
f.FoodName = food.food_name;
foods.Add(f);
}
}
else
Console.WriteLine("No results from term");
JavaScriptSerializer serializer = new JavaScriptSerializer();
str = serializer.Serialize(foods);
return str;
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
HTML
<%@ Page Language="C#" AutoEventWireup="true" Async="True" CodeBehind="default.aspx.cs" Inherits="HELP_Testing._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="scripts/default.js"></script>
<script type="text/javascript" src="scripts/jquery-1.11.1.js"></script>
<title>Healthy Eating Life Planner</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" name="Food Search" id="searchField" />
<button type="submit" onclick="search()">Search</button>
</div>
</form>
</body>
</html>
完整的錯誤消息是:
此時無法啓動異步操作。異步操作只能使用異步處理程序或模塊 或頁生命週期中的某些事件期間啓動。如果執行頁面時發生此異常,請確保頁面標記爲Async = true。此異常也可能表示嘗試調用「異步無效」方法,該方法在ASP.NET請求處理中通常不支持 。相反,異步方法應該返回一個任務,調用者應該等待它」
額外的旁註:事實證明,包裝有一個異步選項,但我們還沒有弄清楚如何使用它。 – mcraen 2014-10-10 12:37:55