【发布时间】:2018-06-12 06:46:39
【问题描述】:
我使用以下 POST 方法创建了 ASP.NET WebAPI:
[HttpPost, Route("")]
public IHttpActionResult Post([FromBody] StudentDto student)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var maxId = conrollerStudents.Max(x => x.ID);
student.ID = ++maxId;
conrollerStudents.Add(student);
InsertStudentIntoDatabase(student);
return CreatedAtRoute("GetStudent", new { id = student.ID }, student);
}
WebAPI 的配置:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
此 API 方法仅适用于 POSTMAN,因为 POST 请求我得到了 201。当我使用以下代码(由 POSTMAN 自动生成)将此请求移动到 JavaScript-Jquery-AJAX 中时。我收到以下错误消息:
{
"Message":"No HTTP resource was found that matches the request URI 'http://localhost:59523/api/students'.",
"MessageDetail":"No action was found on the controller 'Students' that matches the request."
}
这是自动生成的 JavaScript-Jquery-AJAX 代码,碰巧不起作用:
// ...
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:59523/api/students",
"method": "POST",
"headers": {
"content-type": "application/json"
},
"processData": false,
"data": "{\n \"FirstName\": \"Sample\",\n \"LastName\": \"Sample\",\n \"City\": \"Sample\",\n \"ListOfCourses\": []\n}"
};
$.ajax(settings).done(function (response) {
console.log(response);
});
// ...
知道为什么会这样吗?
【问题讨论】:
-
你从哪里调用这个 AJAX ?
-
由按钮点击事件触发。
标签: javascript c# jquery ajax asp.net-web-api