C# 将带有JSON数据的GET请求从Axios发送到Asp.net core ActionResult而不获取(415不支持的媒体类型)
我正试图使用axios向aspnet core发出一个包含JSON数据的GET请求,就像这样C# 将带有JSON数据的GET请求从Axios发送到Asp.net core ActionResult而不获取(415不支持的媒体类型),c#,http,asp.net-core,axios,C#,Http,Asp.net Core,Axios,我正试图使用axios向aspnet core发出一个包含JSON数据的GET请求,就像这样 axios.get("http://localhost/api/tag/getnearby",{ Latitude:24.470901, Longitude:39.612236, RangeInMeters:5000 },{ headers: { 'Content-Type': 'application/json;cha
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不支持的媒体类型错误,并且编译器没有在ActionResult中找到断点
奇怪的是,我尝试过从api客户机(如失眠或邮递员)发出相同的请求,但效果很好
提前感谢使用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)
})
}
后端返回的结果
为什么要在GET请求中发送内容类型?尝试模拟api客户端的标题,认为这会有所帮助。在没有发送内容的情况下发送内容类型请求标题字段仍然是不正确的。而且,FWIW在application/json上发送charset=utf-8也是毫无意义的。