上篇,从最简单的string入手。本篇演示了从请求的输入流中获取实体。api:
public class ValuesController : ApiController { [HttpPost] public string GetData(string name) { return "我爱" + name; } [HttpPost] public string GetData() { var stream = HttpContext.Current.Request.InputStream; byte[] byts = new byte[stream.Length]; stream.Read(byts, 0, (int)stream.Length); //以UTF8形式获取数据 string json = Encoding.UTF8.GetString(byts); Woman woman = JsonConvert.DeserializeObject<Woman>(json); return woman.Age + "的" + woman.Name; } } public class Woman//仅仅为了演示方便 { public string Name{get;set;} public string Age{get;set;} }
js:
var woman = { Name: '刘亦菲', Age: 18 }; $(function () { $('#btn').click(function () { $.ajax({ type: "post", url: "http://localhost:7601/api/values/GetData", data:JSON.stringify(woman), success: function (r) { alert(r); } }); }); });
结果:
过程和结果都非常简单。但这里面蕴含着一个巨大的坑,你如果做Attribute验证的话。后面讲到的时候再谈。
如果Action的参数中含有一个简单类型和实体对象,形如
[HttpPost] public string GetData(string name) { var stream = HttpContext.Current.Request.InputStream; byte[] byts = new byte[stream.Length]; stream.Read(byts, 0, (int)stream.Length); //以UTF8形式获取数据 string json = Encoding.UTF8.GetString(byts); Woman woman = JsonConvert.DeserializeObject<Woman>(json); return name + "喜欢" +woman.Age + "的" + woman.Name; }
只需要在js中将url: "http://localhost:7601/api/values/GetData" 改为 url: "http://localhost:7601/api/values/GetData?name=楼主"即可。则在Action中name参数和实体均能正确获得。
由于比较简单,不再赘述。
值得一提的是,此方法对于复杂类型的实体对象传递,也能非常好的支持。比如Man类型的实体。
public class Person { public string Name { get; set; } public string Age { get; set; } } public class Man : Person { public Woman Wife { get; set; } public List<Woman> Lovers { get; set; } } public class Woman : Person { public int Height { get; set; } public List<DateTime> ExerciseTime { get; set; } }