最近在开发asp.net core时,遇到RequestBody和RequestForm数据提交方式,整理了一下,把结果记录下来。
对于RequestForm一般是接收表单的信息,而RequestBody通常是来接收较为复杂的数据(集合或杂杂对象)在asp.net中很容易区分接收,在action用[FromBody]和[FromForm]来标识就可以,对于客户端来说,区别就要大一些,这里记录两种方式,RestSharp和JQuery的ajax请求两种方式。
服务端
[HttpPost("additem")] public IActionResult AddItem([FromBody]Item item) { return new JsonResult(new { Result = 0, Message = "添加成功",Content=item.ToString() },new Newtonsoft.Json.JsonSerializerSettings ()); } [HttpPost("additem")] public IActionResult AddItem([FromForm]Item item) { return new JsonResult(new { Result = 0, Message = "添加成功" ,Content=item.ToString()},new Newtonsoft.Json.JsonSerializerSettings ()); }
RestSharp方式
在项目中,用Nuget安装RestSharp类库,我用的是v105.2.3。
用RestSharp提交RequestBody和RequestForm相对简单,代码如下:
using System;using RestSharp;namespace RestSharpTest { class Program { static void Main(string[] args) { while (true) { var client = new RestClient("http://localhost:5000"); var request = new RestRequest("additem", Method.POST); request.RequestFormat = DataFormat.Json; Console.WriteLine("1、RequestBody 2、RequestForm"); switch (Console.ReadLine()) { case "1": request.AddJsonBody(new { ID = 111, Name = "张三", Birthday = DateTime.Now }); break; case "2": request.AddObject(new { ID = 111, Name = "张三", Birthday = DateTime.Now }); break; } var response = client.Execute(request); Console.WriteLine(response.Content); } } } }
JQuery中用ajax请求
如果用jquery访问别的web,设置跨域访问(关于跨域访问,查看http://www.cnblogs.com/xishuai/p/aspnet-core-cors.html)
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <script src="bower_components/jquery/dist/jquery.min.js"></script></head><body> <input id="sava1" value="保存RequestForm" type="button"/> <input id="sava2" value="保存RequestBody" type="button" /> <script> $("#sava1").click(function () { $.post("http://localhost:5000/additem", { ID: 112, Name: "李四", Birthday: "2017-01-23" }, function (result) { alert(result.Message+result.Content); },"json") }) $("#sava2").click(function () { $.ajax({ type: "POST", url: "http://localhost:5000/additem", contentType: "application/json", dataType: "json", async: true, data: JSON.stringify({ "ID": 112, "Name": "李四", "Birthday": "2017-01-23 12:12:12" }), success: function (result) { alert(result.Message + result.Content); } }); }) </script></body></html>
一般情况下,web api是用[FromBody],因为一般web api是供app或DeskTop的应用访问,web页面请求用[FromForm],一般情况下web页面是通过表单向后台提交信息。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。