【问题标题】:ASP .net core HttpGet with parameter resulting Bad Request带有参数的 ASP .net 核心 HttpGet 导致错误请求
【发布时间】:2019-04-23 14:05:01
【问题描述】:

所以我有一个使用 Axios 调用我的 C# API 的服务。由于我要选择特定的数据,所以我使用带参数的 get 方法。

这是我的服务:

let response = await Axios.get('/api/get-report', {
   params: filter
});

这是我在 typescript 中的过滤器对象:

export interface FilterModel {
  employeeId?: string;
  Month?: Date;
  from?: Date;
  to?: Date;
}

这是服务器上的模型:

public class AttendanceReportFilterModel
{
    public string EmployeeId { set; get; }
    public DateTime? Month { set; get; }
    public DateTime? From { set; get; }
    public DateTime? To { set; get; }
}

这是我的 C# API:

[HttpGet("get-report")]
public async Task<IActionResult> GetReport(FilterModel filter)
{
    var Detail = await Service.GetReport(filter);
    if (Detail == null)
    {
        return StatusCode(500, "Not Found");
    }

    return Ok(Detail);
}

每当我调用我的服务时,它总是返回Bad Request

有人知道为什么以及如何解决这个问题吗?

【问题讨论】:

  • 当您提出请求时,您正在添加一些参数。你能提供来自网络的网址吗?您发送的日期似乎无效。
  • 显示服务器端定义的FilterModel。还显示从客户端发送的filter 参数。您很可能拥有[ApiController],并且由于缺少或格式错误的参数值,过滤器默认为错误请求。
  • 在您调试时它是否被命中,或者它甚至找不到 Url?而不确定您如何通过身体获取?
  • @Nkosi 你可以在我的帖子上看到我的模型,我已经更新了它。我也已经在使用 [ApiController]

标签: typescript api asp.net-web-api asp.net-core


【解决方案1】:

尝试添加

[来自查询]

public async Task<IActionResult> GetReport([FromQuery] FilterModel filter)

因此,由于您正在绑定到对象,因此您需要说明将它们带到哪里https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.1#customize-model-binding-behavior-with-attributes

或者你可以只用参数来做

public async Task<IActionResult> GetReport(string EmployeeId, DateTime? Month = null, DateTime? FromMonth = null, DateTime? ToMonth = null)

【讨论】:

  • 没有FromUri 只有FromBody, Form, Header, Query, Route, Services 我得用哪一个?
  • @hphp 更新了我的答案。我确实为旧的 aspnet 发布过。核心是 fromQuery
  • @hphp 至少它的请求不错:) 似乎是端点被击中但你的代码出错
  • 啊是的..它被击中了..谢谢...现在我只需要调试我的代码逻辑谢谢
猜你喜欢
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 2016-08-12
相关资源
最近更新 更多