Web Api参数始终为null

时间:2013-01-31 11:10:19

标签: asp.net ajax asp.net-web-api

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

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

以下是通过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");
                    }
                });
            }
        });
    }

4 个答案:

答案 0 :(得分: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');
    }
});

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

=somevalue

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

您可以在this article中了解有关Web Api中的模型绑定的更多信息。

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

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

然后摆脱[FromBody]属性:

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

然后使用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');
    }
});

答案 1 :(得分: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 };
}

更改您要发送的JSON:

{"Value":"test"}

答案 2 :(得分:1)

每当我们调用web api动作并且使用[frombody]参数然后输入参数前缀=时 例如

public string GetActiveEvents([FromBody] string XMLRequestString) {
}

调用上面的web api操作

  1. URI

  2. 2。
      

    User-Agent:Fiddler

         

    内容类型:application / x-www-form-urlencoded

         

    主持人:localhost:54702

         

    内容长度:936

    1. 请求正文=数据
    2. 我希望这会给出明确的想法。

答案 3 :(得分:1)

我和这个和.NET Core Web API只是有一段时间的野兽。所以希望为某人节省时间:对我来说实际问题很简单 - 我没有转换为正确的类型(注意@Darins的答案使用VM而不是字符串)。

模板中的默认类型为string。我想因为我们正在发送字符串化的JSON,我们会看到一个JSON字符串,但事实并非如此。我必须把它做成正确的类型。

E.g。

失败
[EnableCors("AllowAll")]
[HttpPost]
public HttpResponseMessage Post([FromBody]string value)
{
    // Do something with the blog here....

    var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
    return msg;

}

但这很有效。

[EnableCors("AllowAll")]
[HttpPost]
public HttpResponseMessage Post([FromBody]Blog value)
{
    // Do something with the blog here....

   var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
  return msg;

}

Ajax Call

function HandleClick() {

    // Warning - ID's should be hidden in a real application 
    //         - or have covering GUIDs.
    var entityData = {
        "blogId": 2,
        "url": "http://myblog.com/blog1",
        "posts": [
        {
            "postId": 3,
            "title": "Post 1-1",
            "content": "This is post 1 for blog 1",
            "blogId": 2
        },
        {
            "postId": 4,
            "title": "Post 1-2",
            "content": "This is post 2 for blog 1",
            "blogId": 2
        }
        ]
    };


    $.ajax({
        type: "POST",
        url: "http://localhost:64633/api/blogs",
        async: true,
        cache: false,
        crossDomain: true,
        data: JSON.stringify(entityData),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (responseData, textStatus, jqXHR) {
            var value = responseData;
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('POST failed.');
        }
    });

}
相关问题