Web Api 参数始终为空 [英] Web Api Parameter always null

查看:29
本文介绍了Web Api 参数始终为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why is the parameter always null when I call the below Post method with the below ajax?

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

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

Here is the call to the Web API method via ajax:

  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");
                    }
                });
            }
        });
    }

推荐答案

$.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');
    }
});

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

Basically you can have only one parameter of scalar type which is decorated with the [FromBody] attribute and your request needs to use application/x-www-form-urlencoded and the POST payload should look like this:

=somevalue

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

Notice that contrary to standard protocols the parameter name is missing. You are sending only the value.

您可以在 这篇文章.

但当然,这种黑客攻击是件病态的事情.您应该使用视图模型:

But of course this hacking around is a sick thing. You should use a view model:

public class MyViewModel
{
    public string Value { get; set; }
}

然后去掉[FromBody]属性:

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

然后使用 JSON 请求:

and then use a JSON request:

$.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');
    }
});

这篇关于Web Api 参数始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆