首页 > 解决方案 > C# Web Api 调用未从 jquery 调用

问题描述

我正在POST web-api从 jQuery 脚本进行调用,但数据没有绑定。Pagenull

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
    }
}

标签: c#jqueryasp.net-mvcasp.net-web-apidata-binding

解决方案


控制器中没有设置路由/api/sitehit/LogHit。ApiController 的工作方式与常规 MVC 控制器不同。除非您指定,否则操作的名称不是端点的路由。

您可以将路由属性添加到控制器操作。

[Route("LogHit")]
[HttpPost]
public void LogHit(string Page)
{
}

或者(假设控制器上没有其他 HttpPost 方法)将jQueryurl 更改为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

希望这可以帮助。


推荐阅读