hphp
hphp

Reputation: 2272

ASP .net core HttpGet with parameter resulting Bad Request

So I have a service using Axios to call my C# API. Since I want to select specific data, I use a get method with a parameter.

Here's my service:

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

Here's my filter object in typescript:

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

Here's the model on the server:

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

And here's my 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);
}

Whenever I call my service, it always returns Bad Request.

Does anybody know why and how to fix this?

Upvotes: 1

Views: 2810

Answers (1)

Vova Bilyachat
Vova Bilyachat

Reputation: 19494

Try to add

[FromQuery]

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

So since you are doing binding to object you need to say where to take them https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.1#customize-model-binding-behavior-with-attributes.

Or you can do it just with parameters

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

Upvotes: 1

Related Questions