OData / OData/AspNetCoreOData

'The query specified in the URI is not valid' when EnableQueryAttribute is used

Open
#92 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
505
Forks
186
PR merge metrics
No merged PRs in 30d

Description

Versions:

  1. Microsoft.AspNetCore.OData - 7.4.1
  2. Microsoft.AspNetCore.OData.Versioning.ApiExplorer - 4.1.1
  3. .NET Core 3.1.6

Scenario:
When EnableQueryAttribute is used ODATA query throw an error.
In next example please go to odata/lists/companies?$expand=unit.

If update Microsoft.AspNetCore.OData to 7.5.5
Then next one exception is thrown:

An item with the same key has already been added. Key: RequestQueryData

Expected result:
Returns list of companies with expanded 'unit' property.

Actuall result:

{
    "error": {
        "code": "",
        "message": "The query specified in the URI is not valid. Could not find a property named 'unit' on type 'Microsoft.AspNet.OData.Query.Expressions.SelectAllAndExpand_1OfCompany'.",
        "details": [],
        "innererror": {
            "message": "Could not find a property named 'unit' on type 'Microsoft.AspNet.OData.Query.Expressions.SelectAllAndExpand_1OfCompany'.",
            "type": "Microsoft.OData.ODataException",
            "stacktrace": "   at Microsoft.OData.UriParser.SelectExpandBinder.GenerateExpandItem(ExpandTermToken tokenIn)\r\n   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()\r\n   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()\r\n   at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)\r\n   at Microsoft.OData.UriParser.SelectExpandBinder.Bind(ExpandToken expandToken, SelectToken selectToken)\r\n   at Microsoft.OData.UriParser.SelectExpandSemanticBinder.Bind(ODataPathInfo odataPathInfo, ExpandToken expandToken, SelectToken selectToken, ODataUriParserConfiguration configuration, BindingState state)\r\n   at Microsoft.OData.UriParser.ODataQueryOptionParser.ParseSelectAndExpandImplementation(String select, String expand, ODataUriParserConfiguration configuration, ODataPathInfo odataPathInfo)\r\n   at Microsoft.OData.UriParser.ODataQueryOptionParser.ParseSelectAndExpand()\r\n   at Microsoft.AspNet.OData.Query.SelectExpandQueryOption.get_SelectExpandClause()\r\n   at Microsoft.AspNet.OData.Query.Validators.SelectExpandQueryValidator.Validate(SelectExpandQueryOption selectExpandQueryOption, ODataValidationSettings validationSettings)\r\n   at Microsoft.AspNet.OData.Query.SelectExpandQueryOption.Validate(ODataValidationSettings validationSettings)\r\n   at Microsoft.AspNet.OData.Query.Validators.ODataQueryValidator.Validate(ODataQueryOptions options, ODataValidationSettings validationSettings)\r\n   at Microsoft.AspNet.OData.Query.ODataQueryOptions.Validate(ODataValidationSettings validationSettings)\r\n   at Microsoft.AspNet.OData.EnableQueryAttribute.ValidateQuery(HttpRequest request, ODataQueryOptions queryOptions)\r\n   at Microsoft.AspNet.OData.EnableQueryAttribute.CreateAndValidateQueryOptions(HttpRequest request, ODataQueryContext queryContext)\r\n   at Microsoft.AspNet.OData.EnableQueryAttribute.<>c__DisplayClass1_0.<OnActionExecuted>b__1(ODataQueryContext queryContext)\r\n   at Microsoft.AspNet.OData.EnableQueryAttribute.ExecuteQuery(Object responseValue, IQueryable singleResultCollection, IWebApiActionDescriptor actionDescriptor, Func`2 modelFunction, IWebApiRequestMessage request, Func`2 createQueryOptionFunction)\r\n   at Microsoft.AspNet.OData.EnableQueryAttribute.OnActionExecuted(Object responseValue, IQueryable singleResultCollection, IWebApiActionDescriptor actionDescriptor, IWebApiRequestMessage request, Func`2 modelFunction, Func`2 createQueryOptionFunction, Action`1 createResponseAction, Action`3 createErrorAction)"
        }
    }
}

Configurations:

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
      services.AddODataQueryFilter(new ODataPermissionQueryFilter());
      services.AddOData();
  
      services.AddMvc(options =>
      {
          options.EnableEndpointRouting = false;
      }).SetCompatibilityVersion(CompatibilityVersion.Latest);
}
        
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, VersionedODataModelBuilder modelBuilder)
{
      var builder = new ODataConventionModelBuilder(app.ApplicationServices);

      var lists = builder.EntitySet<ODataList>("Lists").EntityType;

      builder.EntitySet<Test>("Test");

      builder.EntitySet<Company>("Companies");

      lists.Collection.Function("Companies")
          .ReturnsCollectionFromEntitySet<Company>("Companies");

      var model = builder.GetEdmModel();

      app.UseMvc(builder =>
      {
          builder.EnableDependencyInjection();
          builder.ServiceProvider.GetRequiredService<ODataOptions>().UrlKeyDelimiter = ODataUrlKeyDelimiter.Parentheses;
          builder.Select().OrderBy().Filter().MaxTop(500).Expand().Count();
          builder.MapODataServiceRoute("odata", "odata", model);
      });
}

Controller code:

TestController.cs
[ApiVersion("1.0")]
[ODataRoutePrefix("Lists")]
public class TestController : ODataController
{
    private TestDbContext _testDbContext { get; set; }

    public TestController(TestDbContext testDbContext)
    {
        _testDbContext = testDbContext;
    }

    [HttpGet]
    [ODataRoute("Companies")]
    [EnableQuery]
    public IQueryable<Company> Companies() => _testDbContext.Companies;
}

QueryFilter:

ODataPermissionQueryFilter.cs
public class ODataPermissionQueryFilter : EnableQueryAttribute
{
    public override void ValidateQuery(HttpRequest request, ODataQueryOptions queryOptions)
    {
        base.ValidateQuery(request, queryOptions);
    }
}

Entities:

Company.cs
public class Company
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public Guid? UnitId { get; set; }

    public Unit Unit { get; set; }
}

TestApplication.zip

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the attached TestApplication and requesting odata/lists/companies?$expand=unit. Read Startup.cs, TestController.cs, ODataPermissionQueryFilter.cs, and Company.cs to trace how EnableQueryAttribute and the OData model handle the expand. Done means the request returns companies with their expanded unit property without either reported exception.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.