How to add a data model to asp.net core web api?
I like to add the following model to the route:
public class SomeComplexDataModel
{
public bool DOSomething { get; set; } = false;
public bool DoThisAndThis { get; set; } = false;
public DateTime StartDateDaily { get; set; }
public DateTime EndDateDaily { get; set; }
public DateTime StartDateMonthly { get; set; }
public DateTime EndDateMonthly { get; set; }
}
This is my controller code:
[HttpGet("SQLite/ExcelReport/")]
public FileResult GetExcelReport(SomeComplexDataModel someComplexDataModel)
{
//Some code here and returning a file
}
Swagger returns this error message:
TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
Is it possible doing it in this way? Whats wrong?
CodePudding user response:
With that signature, it will create an action that uses the GET
method and expects a request body to fill in that SomeComplexDataModel
by default. You cannot pass parameters in the body of a GET
method.
A simple way to fix this would be to change the method that allows passing a request body, POST
would be sufficient in this case.
However if it makes sense to make this a GET
action, you need to instruct it to pass the parameters in a different way. Judging by the name of the route and properties on the object, you could tell it to expect the properties as query parameters. Just apply the [FromQuery]
attribute to the parameter.
[HttpGet("SQLite/ExcelReport/")]
public FileResult GetExcelReport([FromQuery] SomeComplexDataModel someComplexDataModel)
{
//Some code here and returning a file
}
Each property of the model would then be mapped to a query property of the same name. Though I would suggest making all your properties nullable so you can detect the omission of a parameter.
CodePudding user response:
You should change HttpGet to HttpPost !
The HTTP GET method is for requesting a representation of the specified resource. Requests using GET should only retrieve data and hence cannot have body.