使用 Get 方法时状态码为 415 的 Axios 错误

Axios Error with Status Code 415 in Using Get Method

美好的一天,

我在使用 axios.get 时遇到此错误代码。错误代码是 415。我想要做的是,提供 const 对象以将其发送到我的控制器。我尝试调试控制器,但它没有在我的控制器(ASP.NET 核心控制器)中进行。

这是我的示例代码:

// Class that I want to supply
public class User{
    public int? Name {get;set;}
    public DateTime? Bday {get;set;}
}

// My Controller
public async Task<IActionResult> GetUsers([FromBody] User user){
    // Do something here
}

// My js file axios is already imported and working
async searchUser(){
    const user = {
        Name: name,
        Bday: bday
    }

    await axios.get(`/SomePage/GetUsers/`,user).then(response=>{
        // do something here
    }.catch(error=>{console.log(error);});
}

希望有人能帮我找到解决办法。

HTTP 状态代码 415 表示不支持的媒体类型。那就是服务器拒绝接受请求,因为负载格式是不支持的格式。

根据MDN Web Docs

The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.

你能把你的 API 动作 FromBody 改成 FromQuery 吗?从技术上讲,这应该可行。

是的,Jaliya 是对的。由于您正在处理 API 请求,因此您还可以从 Microsoft 查看此文档,了解 ASP.NET Web API 中的参数绑定。 Parameter Binding in ASP.NET Web API

调用axios时传递header

axios.get("https://api.url.com", {headers: {'Content-Type': 'application/json'}