WebApi icon indicating copy to clipboard operation
WebApi copied to clipboard

Create custom response in .NET Core 5 with OData 8 controller

Open cap7ainjack opened this issue 3 years ago • 4 comments

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 avatar Nov 10 '21 12:11 cap7ainjack

@cap7ainjack this is by design. When using EnableQuery, validation is done before the action executes.

ElizabethOkerio avatar Nov 16 '21 18:11 ElizabethOkerio

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?

cap7ainjack avatar Nov 18 '21 10:11 cap7ainjack

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.

sjd2021 avatar Aug 05 '22 18:08 sjd2021

@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": [],

KenitoInc avatar Nov 20 '22 09:11 KenitoInc