我有这个代码:
$.ajax({ type: "POST",url: "/api/slide",cache: false,contentType: "application/json; charset=utf-8",data: '{"Title":"fghfdhgfdgfd"}',dataType: "json",@H_301_3@这是我的控制者:
public class SlideController : ApiController { // POST /api/Slide public void Post(string Title) { }@H_301_3@当我运行代码并调用/ api / Slide时,[标题]没有数据,为空。 @H_301_3@如何将JSON发布到API控制器?
POST http://127.0.0.2:81/api/slide HTTP/1.1 Host: 127.0.0.2:81 Connection: keep-alive Content-Length: 18 Origin: http://127.0.0.2:81 X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML,like Gecko) Chrome/21.0.1180.89 Safari/537.1 Content-Type: application/json; charset=UTF-8 Accept: application/json,text/javascript,*/*; q=0.01 Referer: http://127.0.0.2:81/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Title=fghfdhgfdgfd
定义视图模型:
public class Slideviewmodel { public string Title { get; set; } }@H_301_3@那么您的控制器操作将此视图模型作为参数:
public class SlideController : ApiController { // POST /api/Slide public void Post(Slideviewmodel model) { ... } }@H_301_3@最后调用动作:
$.ajax({ type: 'POST',url: '/api/slide',contentType: 'application/json; charset=utf-8',data: JSON.stringify({ title: "fghfdhgfdgfd" }),success: function() { ... } });@H_301_3@其原因是诸如字符串的简单类型从URI绑定。我还邀请您阅读关于Web API中的模型绑定的following article。