[英]Send GET request with JSON data from Axios to Asp.net core ActionResult without getting (415 Unsupported Media Type)
我正在尝试使用 axios 向 aspnet 核心发出带有 JSON 数据的 GET 请求
axios.get("http://localhost/api/tag/getnearby",{
Latitude:24.470901,
Longitude:39.612236,
RangeInMeters:5000
},{
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': true,
'Access-Control-Request-Headers': 'Content-Type, x-requested-with',
}
})
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err)
})
后端
[HttpGet("getnearby")]
[AllowAnonymous]
public ActionResult GetNearby(GetNearbyRequest request)
{
var tags = Tag.SelectNearby(Convert.ToDouble(request.Longitude),Convert.ToDouble(request.Latitude),Convert.ToUInt32(request.RangeInMeters));
return Ok(new {tags = tags});
}
public class GetNearbyRequest
{
public string Latitude {get;set;}
public string Longitude {get;set;}
public string RangeInMeters {get;set;}
}
但是,我总是在响应中收到415 Unsupported media type错误,并且编译器没有在 ActionResult 中遇到断点。
奇怪的是,我尝试从 api 客户端(如 Insomnia 或 PostMan)执行相同的请求,并且效果很好。
提前致谢
用axios get
方法,传给后台的参数是字符串,不能传json,post方法可以实现。
您可以在后端添加[FromQuery]
。
public ActionResult GetNearby([FromQuery]GetNearbyRequest request)
{
//...
return Ok(request);
}
并且 axios 中的方法get
添加params
。
axios.get("https://localhost:44350/api/Tag/getnearby",
{params:{
Latitude:24.470901,
Longitude:39.612236,
RangeInMeters:5000
}},{
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': true,
'Access-Control-Request-Headers': 'Content-Type, x-requested-with',
}
})
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err)
})
}
后端返回的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.