c# - C# Web Api 调用未从 jquery 调用
问题描述
我正在POST
web-api
从 jQuery 脚本进行调用,但数据没有绑定。Page
是null
jQuery
$("document").ready(function(){
myTimer= setInterval( "StartTimer()", 1000);
});
function StartTimer()
{
$.ajax({
type: 'POST',
contentType: "application/x-www-form-urlencoded",
url: "/api/sitehit/LogHit/", //method Name
data: 'Page=test' ,
dataType: 'text/plain',
error: function (msg) {
alert(msg.responsetext);
}
}).fail(function () {
alert("error logging hit");
}).success(function () {
alert("success logging hit");
});
clearInterval(myTimer);
}
C# 代码
public class SiteHitController : ApiController
{
[HttpPost]
public void LogHit(string Page) // Page not binding
{
var c= Page; // Page is null
}
}
解决方案
控制器中没有设置路由/api/sitehit/LogHit
。ApiController 的工作方式与常规 MVC 控制器不同。除非您指定,否则操作的名称不是端点的路由。
您可以将路由属性添加到控制器操作。
[Route("LogHit")]
[HttpPost]
public void LogHit(string Page)
{
}
或者(假设控制器上没有其他 HttpPost 方法)将jQuery
url 更改为url: '/api/sitehit'
.
有多种方法可以绑定数据,具体取决于您要发送的内容类型。假设您想使用 JSON,您可以执行以下操作。
创建一个模型以绑定并添加[FromBody]
到控制器操作参数:
public class MyModelDto
{
public string Page { get; set; }
}
[Route("LogHit")]
[HttpPost]
public void LogHit([FromBody] MyModelDto model) // add FromBody here
{
// model.Page will contain "test"
}
然后确保您在 ajax 调用中通过使用JSON.stringify()
字符串化数据来发送 JSON。
$.ajax({
type: 'POST',
contentType: "application/json",
url: "/api/sitehit/LogHit",
data: JSON.stringify({Page: 'test'}), // use JSON.stringify()
dataType: 'json',
success: function (data) {
// can use response data here
alert("success logging hit");
},
error: function (msg) {
alert(msg.responsetext);
}
});
这现在应该正确绑定到您的控制器。
如果您要发送表单数据x-www-form-urlencoded
,则使用[FromForm]
而不需要使用JSON.stringify()
,但在这种情况下,参数应以查询字符串形式发送:page=test&prop2=test2
。
希望这可以帮助。
推荐阅读
- java - 我的代码中的 For 循环失败。根本不执行
- javascript - 在javascript中等待获取结果
- javascript - JSX 在 React 中解析但不解析依赖(webpack,babel)
- python - bulk_insert 不会将值插入可空字段
- java - 检查是否在 URL 中指定了参数
- python - 如何在 pycairo 中快速绘制大量多边形?
- ruby - 我可以在类中包含模块方法吗?
- r - R中str_detect函数中的字边界
- excel - Pandas ExcelWriter 是否适用于 excel 365,或者它支持哪个版本的 excel
- mysql - 在 MySql 的另一个查询中进行查询