c# - 将带有 JSON 数据的 GET 请求从 Axios 发送到 Asp.net core ActionResult 而不获取(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 中遇到断点。
奇怪的是,我尝试从像 Insomnia 或 PostMan 这样的 api 客户端发出相同的请求,并且效果很好。
提前致谢
解决方案
用axiosget
方法,传给后台的参数是string,不能传json,post方法可以实现。
您可以[FromQuery]
在后端添加。
public ActionResult GetNearby([FromQuery]GetNearbyRequest request)
{
//...
return Ok(request);
}
并且get
axios 中的方法应该添加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)
})
}
后端返回的结果。
推荐阅读
- java - Thread.Interrupt() 不起作用,我真的不明白为什么
- android - Jacoco Gradle Plugin:如何从子模块生成检测的 jar 文件?
- python - 在 python 后端业务逻辑中,我如何以及在哪个模块中引用 Django 用户上传的文件?
- reactjs - TypeError:不是子组件中的函数错误
- intellij-idea - Intellij 服务图:未找到支持的 Web 框架的服务模块
- android - 在范围内找不到“问候”
- php - 在非洲国家/地区的 Woocommerce 结帐中禁用邮政编码/邮政编码
- php - Laravel 5.8:在控制器上正确使用请求
- c# - 无法在 RequestFilterAttribute 中获取请求正文
- android - 使用 PackagingOptions 的目的是什么?