我在进行Ajax调用时遇到“404 Not Found”, 也许我不明白路由是如何工作的......
function ApproveAlert(ID) {
$.ajaxPost('/api/DeviceApi/ApproveAlertNew', { 'ID': ID }, function (data) {
... get error "404 Not Found"
}, null);
}
在我的mvc4 C#app中,我有一个溃败配置:
RouteTable.Routes.MapHttpRoute(
name: "defaultapiaction",
routeTemplate: "api/{controller}/{action}"
);
RouteTable.Routes.MapHttpRoute(
name: "defaultapiid",
routeTemplate: "api/{controller}/{action}/{id}"
);
和apicontroller:
public class DeviceApiController : ApiController
{
//
// GET: /DeviceApi/
[HttpPost]
public bool ApproveAlertNew(int ID)
{
..do
}
答案 0 :(得分:0)
Web API控制器不像MVC控制器那样使用“Actions”。 Web API控制器也不真正使用[HttpPost]
,[HttpGet]
属性。他们根据ApiControllers内部方法的名称发送请求。我建议稍微阅读一下MVC的Web API差异,因为它很相似,但有时很难启动和运行......
这是我用于测试的Web API中的一些非常通用的示例。我没有JavaScript发布到此API,因为我是从.NET WPF应用程序发布的。您将发布到“/重要”而不是“/重要/发布”希望这会让您走上正确的轨道......
WebAPIConfig.cs(路线):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace ArrayTest.WebAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
API控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ArrayTest.Models;
using System.Threading;
namespace ArrayTest.WebAPI.Controllers
{
public class ImportantController : ApiController
{
// POST api/important
public HttpResponseMessage Post(ImportantList values)
{
//manipulate values received from client
for (int i = 0; i < values.ImportantIDs.Count; i++)
{
values.ImportantIDs[i] = values.ImportantIDs[i] * 2;
}
//perhaps save to database, send emails, etc... here.
Thread.Sleep(5000); //simulate important work
//in my case I am changing values and sending the values back here.
return Request.CreateResponse(HttpStatusCode.Created, values);
}
}
}
型号:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArrayTest.Models
{
public class ImportantList
{
public List<int> ImportantIDs { get; set; }
}
}
答案 1 :(得分:0)
你可以尝试:
function ApproveAlert(ID) {
$.ajax({
type: 'POST',
url: "/api/DeviceApi/ApproveAlertNew",
data: {
ID: ID
},
success: function (data) {
//Handle your success
},
error: function (jqXHR, textStatus, errorThrown) {
//Handle error
}
});
}