我创建了这个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 () {
}
});
}
这是我的网络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调用没有成功?
答案 0 :(得分:2)
function getAssociatedProperties(callback, error) {
$.ajax({
url: '/api/LayerProperty', // <--- You do not need the 'get' here, but you do need the /api/
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: 5,
crossDomain: true,
success: callback,
error: function () {
}
});
}
答案 1 :(得分:0)
你能用下面的代码改变你的方法吗?
[HttpGet]
public IEnumerable<string> get()
{
return new string[] { "value1", "value2" };
}
答案 2 :(得分:0)
将控制器名称与您的控制器一起使用然后它将从ajax请求触发,目前您没有在mvc中使用正确的命名约定。
您的
public class LayerProperty : ApiController
我的
public class LayerPropertyController : ApiController
答案 3 :(得分:-1)
你的网址有错误。
function getAssociatedProperties(callback, error) {
$.ajax({
url: '/api/LayerProperty/get',
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: 5,
crossDomain: true,
success: callback,
error: function () {
}
});
}