【发布时间】:2017-12-10 15:38:57
【问题描述】:
我创建了这个 ajax 函数:
function getAssociatedProperties(callback, error) {
$.ajax({
url: '/LayerProperty/get',
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: 5,
crossDomain: true,
success: callback,
error: function () {
}
});
}
这是我的 web api 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace GeomindMobile.Controllers
{
public class LayerProperty : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
每当触发 ajax 函数时,我都会收到此错误:
http://localhost/LayerProperty/get 404 (Not Found)
更新
Here is my RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我的代码有什么问题?为什么 ajax 调用不成功?
【问题讨论】:
-
你应该只通过 api/LayerProperty/5 而不是 api/LayerProperty/Get/5
-
crossDomain: true你为什么用这个?是否需要在同一个域上模拟跨域请求?因为这就是此设置的作用。 -
您能否也发布您的路由配置?
-
@juunas 请看更新
-
我认为那是你的 MVC 路由而不是 WEB API...尝试发布一个 Web API...
标签: ajax asp.net-mvc asp.net-web-api