ApiController在POST中接收null

时间:2013-08-14 05:13:17

标签: json webforms asp.net-apicontroller

你会想:这有多难?嗯,似乎很好。

运行jQuery:

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/api/TEST",
            data: {"":{close:true, user: "<%: uuid %>" }},
            success: null,
            dataType: "json"
        });

我正在使用asp.net webforms,ApiContoller试图发布一些简单的数据。

public class TESTController : ApiController {
    // GET api/<controller>
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id) {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value) {
        string k = ";;";


    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value) {
    }

    // DELETE api/<controller>/5
    public void Delete(int id) {
    }
}

调用POST方法,但值始终为null。我试过在没有空引号的情况下更改ajax帖子中的数据,但无济于事。

1 个答案:

答案 0 :(得分:0)

显然,浏览博客数小时后,您需要在上面的例子中进行/编辑:

public string Post(tester test) {
    string k = ";;";

    return k;
}

添加一个类

public class tester {
    public string user { get; set; }
    public bool close { get; set; }
}

并将AJAX更改为

    var value = {close:true, user: "<%: uuid %>" };
    $.ajax({
        type: "POST",
        contentType: "application/json;charset=utf-8",
        url: "/api/TEST/",
        data: JSON.stringify(value)
    }).done(function(msg) {
        alert("done"+msg); 
    });
相关问题