Web Api参数始终为null

dan*_*iel 35 asp.net ajax asp.net-web-api

当我用下面的ajax调用下面的Post方法时,为什么参数总是为null?

public IEnumerable<string> Post([FromBody]string value)
{
    return new string[] { "value1", "value2", value };
}
Run Code Online (Sandbox Code Playgroud)

这是通过ajax调用Web API方法:

  function SearchText() {
        $("#txtSearch").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "api/search/",
                    data: "test",
                    dataType: "text",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 60

$.ajax({
    url: '/api/search',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    data: '=' + encodeURIComponent(request.term),
    success: function (data) {
        response(data.d);
    },
    error: function (result) {
        alert('Error');
    }
});
Run Code Online (Sandbox Code Playgroud)

基本上你只能有一个标量类型参数,它用[FromBody]属性装饰,你的请求需要使用application/x-www-form-urlencoded,POST有效负载应如下所示:

=somevalue
Run Code Online (Sandbox Code Playgroud)

请注意,与标准协议相反,缺少参数名称.您只发送值.

您可以阅读有关Web Api中的模型绑定如何工作的更多信息this article.

但当然,这种黑客行为是一种生病的事情.您应该使用视图模型:

public class MyViewModel
{
    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后摆脱[FromBody]属性:

public IEnumerable<string> Post(MyViewModel model)
{
    return new string[] { "value1", "value2", model.Value };
}
Run Code Online (Sandbox Code Playgroud)

然后使用JSON请求:

$.ajax({
    url: '/api/search',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ value: request.term }),
    success: function (data) {
        response(data.d);
    },
    error: function (result) {
        alert('Error');
    }
});
Run Code Online (Sandbox Code Playgroud)


Mar*_*nes 14

您不能对[FromBody]具有JSON内容类型的属性使用简单类型.虽然Visual Studio中的默认值具有来自body的字符串,但这适用于application/x-www-form-urlencoded内容类型.

将字符串值作为属性放在基本模型类上,并且反序列化器将起作用.

public class SimpleModel()
{
    public string Value {get;set;}
}

public IEnumerable<string> Post([FromBody]SimpleModel model)
{
    return new string[] { "value1", "value2", model.Value };
}
Run Code Online (Sandbox Code Playgroud)

将您要发送的JSON更改为:

{"Value":"test"}
Run Code Online (Sandbox Code Playgroud)