通常情况下,这个错误是由于路由错误或请求控制器动作不正确引起的。您可以检查以下几个方面,来解决这个问题:
确认路由配置:确保你的路由配置与你的AJAX请求匹配。你可以在控制器或Startup.cs文件中检查路由配置。
确认Controller的动作方法:确保你的Controller中有对应的动作方法,且命名正确。你可以使用Log信息检查请求是否到达了正确的Controller以及对应的动作方法。
确认请求头文件:你可以使用浏览器开发者工具检查请求头文件,查看是否包含了正确的请求类型和内容类型。你也可以添加一个JSON对象到请求的body中,确保请求正常发送。
示例代码:
路由配置:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
Controller代码:
[Route("api/[controller]")]
[ApiController]
public class SampleController : ControllerBase
{
[HttpPost]
[Route("[action]")]
public IActionResult UpdateRecord([FromBody] SampleRequest sampleRequest)
{
//Logic
return Ok("Record updated successfully.");
}
}
AJAX请求代码:
$.ajax({
url: '/api/Sample/UpdateRecord',
type: 'POST',
data: JSON.stringify(sampleRequest),
contentType: 'application/json;charset=utf-8',
success: function (response) {
//Logic
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.responseText);
}
});