Vue.js GET请求因参数问题无法调用ASP.NET后端API
解决Vue调用ASP.NET GET API时动态参数无法命中后端的问题
问题核心
你的问题和var/let数据类型无关,根源是动态拼接的参数字符串包含&等URL特殊字符,未进行URL编码,导致ASP.NET路由解析时无法识别完整的parameterString路由参数。直接传字符串"ul"时没有特殊字符,所以路由能匹配成功。
方案1:对路由参数进行URL编码
前端拼接参数后,用encodeURIComponent()对整个参数字符串编码,确保特殊字符被正确转义,后端无需修改路由:
修改前端API调用代码:
var ul = `FilterViewID=NA&@FromDate=${reportFormatDate( this.report.fromDate )}&@ToDate=${reportFormatDate(this.report.toDate)}&@Location=${ this.report.location }&@CatCode=${this.report.category}&@EventID=${ this.report.event }&@DepartmentCode=${this.report.department}&@OrderType=1&@id=065631`; alert(ul); // 对参数字符串进行URL编码 const encodedUl = encodeURIComponent(ul); await this.$http .get(`/api/common/get-digest/${encodedUl}`) .then((response) => { this.passingString = response.data.PassingString; }) .catch((error) => { ShowError(this.$toast, error.message); });
方案2:改用查询参数传递(更推荐)
GET请求传递复杂参数时,用查询字符串(Query String)比路由参数更规范,也能避免编码问题:
后端修改路由
[Route("get-digest")] // 移除路由中的{parameterString} [HttpGet] public IHttpActionResult GetDigestString() { // 从查询字符串中获取完整参数串 var parameterString = Request.RequestUri.Query.TrimStart('?'); return Ok(parameterString); }
前端修改API调用
可以选择直接拼接查询字符串,或者利用请求库的params参数自动处理编码(假设$http是axios实例):
// 方式1:直接拼接查询字符串 await this.$http .get(`/api/common/get-digest?${ul}`) .then((response) => { this.passingString = response.data.PassingString; }) .catch((error) => { ShowError(this.$toast, error.message); }); // 方式2:用params传递(更规范,自动编码) const params = { FilterViewID: "NA", "@FromDate": reportFormatDate(this.report.fromDate), "@ToDate": reportFormatDate(this.report.toDate), "@Location": this.report.location, "@CatCode": this.report.category, "@EventID": this.report.event, "@DepartmentCode": this.report.department, OrderType: 1, id: "065631" }; await this.$http .get(`/api/common/get-digest`, { params }) .then((response) => { this.passingString = response.data.PassingString; }) .catch((error) => { ShowError(this.$toast, error.message); });
内容的提问来源于stack exchange,提问作者Kasun sunil
相关产品推荐
相关产品推荐

