这通常需要 2-4 秒,这对于它正在做的工作来说似乎太长了。这是 AJAX:
$("#IngTable").html("<center><img src=../img/loading.gif /></center>");
var search = document.getElementById("IngSearch").value;
var apiLink = "/API/Ingredient/Search?search=" + search;
$.ajaxSetup({ accepts: "application/json" });
$.ajax({
url: apiLink,
type: "GET",
success: function(data) {
var ingredients = JSON.parse(data);
var htmlIngred = "";
for (var i = 0; i < ingredients.length; i++) {
htmlIngred += "<tbody><td><span>" + ingredients[i].Name + "</span></td><td><a class='btn btn-success btn-mini' onclick='addIngred(" + ingredients[i].IngredientId + ");'>Add</a></td></tbody>";
}
document.getElementById("IngTable").innerHTML = htmlIngred;
},
error: function (a, b, c) { }
});
这是 Web API 控制器:
[HttpGet]
public string IngredientSearch(string search)
{
var sw = Stopwatch.StartNew();
var db = new Glubee.Model.GlubeeEntities();
var results = db.Ingredients.Where(x => x.Name.Contains(search)).ToArray();
sw.Stop();
return JsonConvert.SerializeObject(results);
}
配料表中只有 16 件东西,每件不超过 20 个字符。
有谁知道问题可能出在哪里,这使得它需要这么长时间?
编辑:如果有帮助,这是我的 Global.asax.cs 页面:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
这是我的 RouteConfig:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}