首页 > 解决方案 > 将带有 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 客户端发出相同的请求,并且效果很好。

提前致谢

标签: c#httpasp.net-coreaxios

解决方案


用axiosget方法,传给后台的参数是string,不能传json,post方法可以实现。

您可以[FromQuery]在后端添加。

    public ActionResult GetNearby([FromQuery]GetNearbyRequest request)
    {
        //...
        return Ok(request);
    }

并且getaxios 中的方法应该添加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)
              })
            }

后端返回的结果。

在此处输入图像描述


推荐阅读