前端向后端传值.net提供了很多中绑定方式,之前一直没有用过,测试整理了一下,前端传递方式和后端的接收方式。
在测试中前端使用的是axios,后端是.net core web api。
FromBody
1 axios({ 2 headers: { 3 "Content-Type": "application/json;" 4 }, 5 method: 'post', 6 url: '/api/Dev/AddTaskQueue', 7 data: JSON.stringify({ "value": "aaa" }) 8 }); 9 10 [HttpPost("AddTaskQueue")] 11 public void AddTaskQueue([FromBody] data value) 12 { 13 14 15 }
FromForm
1 var f = new FormData(); 2 f.append("value", "333"); 3 axios({ 4 headers: { 5 'Content-Type': 'multipart/form-data' 6 }, 7 method: 'post', 8 url: '/api/Dev/AddTaskQueue1', 9 data: f 10 }); 11 12 [HttpPost("AddTaskQueue1")] 13 public void AddTaskQueue1([FromForm] string value) 14 { 15 var a = 2; 16 }
FromHeader
1 axios({ 2 headers: { 3 "Content-Type": "application/json;", 4 value: "sdf" 5 }, 6 method: 'post', 7 url: '/api/Dev/AddTaskQueue2', 8 data: JSON.stringify({ "value": "aaa" }) 9 }); 10 11 [HttpPost("AddTaskQueue2")] 12 public void AddTaskQueue2([FromHeader] string value) 13 { 14 var a = 2; 15 }
FromQuery
1 axios({ 2 headers: { 3 "Content-Type": "application/json;" 4 }, 5 method: 'post', 6 url: '/api/Dev/AddTaskQueue3?value=33', 7 data: JSON.stringify({ "value": "aaa" }) 8 }); 9 10 [HttpPost("AddTaskQueue3")] 11 public void AddTaskQueue3([FromQuery] string value) 12 { 13 var a = 2; 14 }
FromRoute
1 axios({ 2 headers: { 3 "Content-Type": "application/json;" 4 }, 5 method: 'post', 6 url: '/api/Dev/AddTaskQueue4/23/43', 7 data: JSON.stringify({ "value": "aaa" }) 8 }); 9 10 [Route("/api/Dev/AddTaskQueue4/{facilityId}/{bandwidthChange}")] 11 [HttpPost("AddTaskQueue4")] 12 public void AddTaskQueue4([FromRoute] int facilityId, [FromRoute] int bandwidthChange) 13 { 14 var a = 2; 15 }
FromServices
1 axios({ 2 headers: { 3 "Content-Type": "application/json;" 4 }, 5 method: 'post', 6 url: '/api/Dev/AddTaskQueue5', 7 data: JSON.stringify({ "value": "aaa" }) 8 }); 9 10 [HttpPost("AddTaskQueue5")] 11 public void AddTaskQueue5([FromServices] IArticleService accountService, data value) 12 { 13 var a = 2; 14 }