WebApi
WebApi copied to clipboard
Create custom response in .NET Core 5 with OData 8 controller
I'm using OData 8 in .NET Core 5 with the [EnableQuery] attribute. Problem is when I want to return Problem() or BadRequest("Some message"), the API always returns some default OData BadRequest and never the message I wanted (only when [EnableQuery] attribute is there).
[HttpGet]
[EnableQuery(EnsureStableOrdering = false )]
public IActionResult GetList(ODataQueryOptions<List> queryOptions)
{
if (queryOptions.Filter == null)
{
return BadRequest( "Filter is required for this endpoind!" );
}
try
{
queryOptions.Filter.Validator = new OdataCustomFilterValidator();
this.BaseValidateQueryOptions(queryOptions);
}
catch (ODataException ex)
{
return this.BadRequest(ex.Message);
}
IQueryable<List> list = this._service.GetList();
return this.Ok(list);
}
So in the above example, if the code gets to the first IF, i do not recieve this message but ALWAYS the same Odata error:
{ "error": { "code": "", "message": "The query specified in the URI is not valid. The requested resource is not a collection. Query options $filter, $orderby, $count, $skip, and $top can be applied only on collections.", "details": [],
@cap7ainjack this is by design. When using EnableQuery, validation is done before the action executes.
To done validation before action is one thing. This is OK. But case is when there are no validation problem, query if fine and I want to return BadRequest with custom message. It still returns validation error and not my custom error text
You are telling me it is by design to return query validation error when there is no such error?
Yea.. this is causing some very unfortunate issues. I use this to override MaxTop in some endpoints and need to return a different response which I can see is perfectly valid without that post-validation check.
@cap7ainjack For you to get that error message in the response, there must be a validation issue in your query options. The Action Filter will always short circuit the request pipeline.
{ "error": { "code": "", "message": "The query specified in the URI is not valid. The requested resource is not a collection. Query options $filter, $orderby, $count, $skip, and $top can be applied only on collections.", "details": [],