Home > Software engineering >  OData .Net Core 6 Only Returns Data With No Query String
OData .Net Core 6 Only Returns Data With No Query String

Time:08-27

We are upgrading to .NET Core 6 and our previous implementation of OData is no longer working. We previously had our action as follows:

public class SalesOrdersController : Controller
{
    ...
    [HttpGet]
    [EnableQuery]
    public IEnumerable<Location> GetLocationsQuery()
    {
         return _context.Locations;
    }
    ...
}

Calling this would return data as expected:

http://localhost:5017/SalesOrders/GetLocationsQuery?$select=Id

  [{"Id":2},{"Id":6},{"Id":8},{"Id":9},{"Id":10},{"Id":11},{"Id":12},{"Id":13},{"Id":14},{"Id":3},{"Id":1}]

However, when I do the same with OData 8 (configuration below) I get the following:

"Message": "The query specified in the URI is not valid. The property 'Name' cannot be used in the $filter query option.",
"ExceptionMessage": "The property 'Name' cannot be used in the $filter query option.",
"ExceptionType":"Microsoft.OData.ODataException",
"StackTrace":
at Microsoft.AspNetCore.OData.Query.Validator.FilterQueryValidator.ValidateSingleValuePropertyAccessNode(SingleValuePropertyAccessNode propertyAccessNode, ODataValidationSettings settings) at Microsoft.AspNetCore.OData.Query.Validator.FilterQueryValidator.ValidateSingleValueFunctionCallNode(SingleValueFunctionCallNode node, ODataValidationSettings settings) at Microsoft.AspNetCore.OData.Query.Validator.FilterQueryValidator.ValidateSingleValueFunctionCallNode(SingleValueFunctionCallNode node, ODataValidationSettings settings)
at Microsoft.AspNetCore.OData.Query.Validator.ODataQueryValidator.Validate(ODataQueryOptions options, ODataValidationSettings validationSettings) at Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.ValidateQuery(HttpRequest request, ODataQueryOptions queryOptions) at Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.OnActionExecuting(ActionExecutingContext actionExecutingContext)

I've tried configuring OData on Startup as follows. I can get data back if I leave all query components off, but when I add the $select=Id it never comes back.

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddControllers().AddOData(options.Count().Filter().Expand().Select().OrderBy().SetMaxTop(10000));
}

Any help would be appreciated.

CodePudding user response:

You are missing NewtonsoftJson:

Install two Nuget packages ‎‎Microsoft.AspNetCore.OData.NewtonsoftJson and ‎‎Microsoft.AspNetCore.MVC.NewtonsoftJson.

Then in Program. cs:

builder.Services.AddControllers().AddOData(options => options.Count().Filter().Expand().Select().OrderBy().SetMaxTop(10000)).AddODataNewtonsoftJson();

It worked for me.

  • Related