【问题标题】:How to send object to through axios get method from react to .NET API?如何通过axios get方法将对象发送到对.NET API的反应?
【发布时间】:2022-01-04 10:43:24
【问题描述】:

我有 .NET API 示例:

[Route("[controller]")]
[ApiController]
public class UserController : ControllerBase
{
    [HttpGet("GetUser")]
    public ActionResult GetUserDetails(User userReq)
    {
        var response = service.GetUser(userReq);
        return Ok(response);
    }
}

和用户类示例:

public class User
{
        public int? ID { get; set; }
        public string Name { get; set; }
        public int? Age { get; set; }
        public char? Gender { get; set; }
        public string Email { get; set; }
        public int? Phone { get; set; }
}

我在 React 中通过 axios 以下面的方式调用 API,示例:

axios.get(String(APIUrls.GetUser),
{
    params: {
        ID: null,
        Name: null,
        Age: null,
        Gender: null,
        Email: null,
        Phone: null
    },
}).then(response => {
    console.log(response.data);
})
.catch((err) => {
    console.log(err);
});

我可以通过邮递员获得回复,但是当我从我的应用程序中尝试时,它不起作用。

错误

状态码:415

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"xxxxxxxxxxxx:00000005"}

【问题讨论】:

  • 尝试在控制器类上添加 [Produces("application/json")]
  • 嗨,彼得,API 工作正常,我正在通过邮递员收到回复。
  • 它肯定可以正常工作,但值得一试,因为它不会改变 api 输出,只会改变响应的标题。
  • 我试过了,还是报同样的错误。

标签: reactjs axios asp.net-core-webapi


【解决方案1】:

添加[FromQuery]属性指定来源:

[HttpGet("GetUser")]

public ActionResult GetUserDetails([FromQuery] User userReq)
{
    //...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 2021-12-12
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2020-04-06
    • 2021-02-20
    相关资源
    最近更新 更多