diff --git a/src/Microsoft.AspNetCore.OData/Query/EnableQueryAttribute.cs b/src/Microsoft.AspNetCore.OData/Query/EnableQueryAttribute.cs index 31f12d35b..3cfe4ff86 100644 --- a/src/Microsoft.AspNetCore.OData/Query/EnableQueryAttribute.cs +++ b/src/Microsoft.AspNetCore.OData/Query/EnableQueryAttribute.cs @@ -542,7 +542,7 @@ private ODataQueryOptions CreateAndValidateQueryOptions(HttpRequest request, ODa { RequestQueryData requestQueryData = request.HttpContext.Items[nameof(RequestQueryData)] as RequestQueryData; - if (requestQueryData.QueryValidationRunBeforeActionExecution) + if (requestQueryData != null && requestQueryData.QueryValidationRunBeforeActionExecution) { return requestQueryData.ProcessedQueryOptions; } diff --git a/test/Microsoft.AspNetCore.OData.Tests/Query/EnableQueryAttributeTests.cs b/test/Microsoft.AspNetCore.OData.Tests/Query/EnableQueryAttributeTests.cs index 077f675a9..8d75804c1 100644 --- a/test/Microsoft.AspNetCore.OData.Tests/Query/EnableQueryAttributeTests.cs +++ b/test/Microsoft.AspNetCore.OData.Tests/Query/EnableQueryAttributeTests.cs @@ -318,6 +318,43 @@ private static IEnumerable CreateDescriptors(string return descriptors; } + [Fact] + public void Derived_Class_Can_Unit_Test_When_OnActionExecuted_Is_Overridden() + { + // https://github.com/OData/AspNetCoreOData/issues/239: unit tests for derived classes fail because RequestQueryOptions missing from HttpContext.Items + IEdmModel model = new CustomersModelWithInheritance().Model; + + var request = RequestFactory.Create("Get", "http://localhost/Customers?$filter=Id+eq+1", opt => opt.AddRouteComponents("odata", model, services => { }).Filter()); + + ODataUriParser parser = new ODataUriParser(model, new Uri("Customers", UriKind.Relative)); + HttpContext httpContext = request.HttpContext; + + Assert.NotNull(httpContext.RequestServices); + + httpContext.Request.Method = "Get"; + request.Configure("odata", model, parser.ParsePath()); + ActionDescriptor actionDescriptor = CreateDescriptors("CustomersController", typeof(CustomersController)) + .First(descriptor => descriptor.ActionName.StartsWith("Get", StringComparison.OrdinalIgnoreCase)); + ActionContext actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor); + + ActionExecutedContext context = new ActionExecutedContext(actionContext, new List(), new CustomersController()); + context.Result = new ObjectResult(new List() { new Customer { Id = 1, Name = "John Doe" } }) { StatusCode = 200 }; + + MyEnableQueryAttribute attribute = new MyEnableQueryAttribute(); + + // Act and Assert + ExceptionAssert.DoesNotThrow(() => attribute.OnActionExecuted(context)); + + } + + private class MyEnableQueryAttribute : EnableQueryAttribute + { + public override void OnActionExecuted(ActionExecutedContext actionExecutedContext) + { + base.OnActionExecuted(actionExecutedContext); + } + } + #if NETCORE // Following functionality is only supported in NetCore. [Fact] public void OnActionExecuting_Throws_Null_Context()