开发手册 欢迎您!
软件开发者资料库

ASP.NET Core Action接收VUE中Axios提交Form表单参数方法及示例代码

本文主要介绍ASP.NET Core中,前端使用Vue.js通过Axios提交get请求和提交Form表单的参数,后台接收参数([FromQuery] [FromRoute] [FromForm] [FromBody] [FromHeader] )方法,以及相关使用的示例代码。

1、使用Axios提交表单

与JQuery的不同,使用Axios提交POST请求,要求注意设置一下Content-Typeapplication/x-www-form-urlencoded;charset=UTF-8 和 qs.stringify(data)

通用组件示例代码如下,

import axios from 'axios'import qs from 'qs'// create an axios instanceconst service = axios.create({  //baseURL: process.env.BASE_API, // api的base_url  headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}, // `headers` 是即将被发送的自定义请求头  // `transformRequest` 允许在向服务器发送前,修改请求数据  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream  transformRequest: [function (data) {    // 对 data 进行任意转换处理    return qs.stringify(data)  }],  timeout: 5000 // request timeout})export default service

1) 执行get请求

//导入组件,from后面要接照实际写import service from '@/utils/request'      let that = this;      service.get('/api/service/GetLotteryInfo', {          params: {            status: 1          }        })        .then(function(response) {          if (response.data.status == "ok") {            //alert(response.data.message);            debugger;            for (var item in response.data.data) {              that.lottery.push({                label: response.data.data[item].name,                value: response.data.data[item].id              });            }            //that.$message.success('提交成功!')          } else {            that.$message.error(response.data.message);          }          console.log(response);        })        .catch(function(error) {          console.log(error);        });

2) 执行POST请求

 service.post('/api/service/SaveAwards',{name:'wonhero',title:'wonhero',lId:1,desc:'lottery'})          .then(function(response) {            if (response.data.status == "ok") {              that.$message.success('提交成功!')            } else {              that.$message.error(response.data.message);            }            console.log(response);          })          .catch(function(error) {            console.log(error);            that.$message.error(error);          });

2、ASP.NET Core后台接收参数

1) get请求参数比较少

public ActionResult GetAwardsList(int id)

2) get请求参数或较复杂

public ActionResult  Get([FromQuery(Name = "identifier")] int id, [FromServices] IOrderService orderService) 

或者

public ActionResult  Get([FromQuery(Name = "identifier")] int id, [FromRoute]  int orderId) 

或者

public ActionResult  Get([FromQuery(Name = "identifier")] int id, [FromHeader] string token) 

2) post请求参数

public class Pet{    public string Name { get; set; }    [FromQuery] // Attribute is ignored.    public string Breed { get; set; }}
public ActionResult Create([FromBody] Pet pet)

或者

public ActionResult Create([FromForm] Pet pet)

[FromQuery]: 从查询字符串中获取值。

[FromRoute] : 从路线数据获取值。

[FromForm] : 从发布的表单字段中获取值。

[FromBody] : 从请求主体获取值。

[FromHeader] : 从HTTP的header中获取值。

相关文档model-binding