Repository navigation
Description
When the browser sends an "OPTIONS" pre-flight request for an OData endpoint, the response may be a 500 error when it should not be.
A simple "Get" action on an Cors attributed ODataController like the following will succeed:
[EnableCors(origins: "http://localhost:52135", headers: "*", methods: "*")]
public class SampleController : ODataController
{
[EnableQuery]
public IQueryable<JobDTO> Get()
{... }
However a call to an action in the same controller with a "delete" verb and an argument like this fails:
public async Task<IHttpActionResult> Delete([FromODataUri] Guid key)
{...}
Sample Error Message:
{
"error":{
"code":"","message":"An error has occurred.","innererror":{
"message":"Object reference not set to an instance of an object.","type":
"System.NullReferenceException","stacktrace":"
at
System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.Create405Response(HttpControllerContext controllerContext, IEnumerable1 allowedCandidates)\r\n
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.CreateSelectionError(HttpControllerContext controllerContext)\r\n
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n
at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n
at System.Web.Http.Tracing.Tracers.HttpActionSelectorTracer.<>c__DisplayClass2.<System.Web.Http.Controllers.IHttpActionSelector.SelectAction>b__0()\r\n
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action1 beginTrace, Action execute, Action1 endTrace, Action1 errorTrace)\r\n
at System.Web.Http.Tracing.Tracers.HttpActionSelectorTracer.System.Web.Http.Controllers.IHttpActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n
at System.Web.OData.Routing.ODataActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n
at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.SelectAction(HttpRequestMessage request, IHttpRouteData routeData, HttpConfiguration config)\r\n
at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider(HttpRequestMessage request)\r\n
at System.Web.Http.Cors.Tracing.CorsPolicyProviderFactoryTracer.<>c__DisplayClass3.<GetCorsPolicyProvider>b__1()\r\n
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action1 beginTrace, Action execute, Action1 endTrace, Action1 errorTrace)\r\n
at System.Web.Http.Cors.Tracing.CorsPolicyProviderFactoryTracer.GetCorsPolicyProvider(HttpRequestMessage request)\r\n at System.Web.Http.Cors.CorsMessageHandler.<GetCorsPolicyAsync>d__10.MoveNext()
\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n
at System.Web.Http.Cors.CorsMessageHandler.<HandleCorsPreflightRequestAsync>d__b.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at
System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0.MoveNext()"
}
}
}
To summarize where this appears to be going wrong:
IHttpRouteData routeData = config.Routes.GetRouteData(request);
if (routeData == null)
{
// No route data found for selecting action with EnableCorsAttribute, thus no ICorsPolicyProvider is returned
// and let the CorsMessageHandler flow the request to the normal Web API pipeline.
return null;
}
actionDescriptor = SelectAction(targetRequest, routeData, config);
- When GetRouteData(request) is called it has side-effects on the request object it is passed (particularly for an Odata route).
- There is a later dependency on those side-effects in the SelectAction() implementation (particularly for an Odata route).
- IFF the expected side-effects are not present\observed the action selection logic “falls-back” (incorrectly)to simple WebApi selection semantics.
It would seem (to a naive observer) that simply sending the same "targetRequest" through both calls would resolve this troubling issue. Can someone who is more familiar please have a look and tell me if this is a bug or whether I may be doing something wrong? Obviously I think "success" should be defined as a fully functional OData service protected by attribute based Cors.
From: Coldplex 2231
Activity
xmichaelx commentedon Jun 15, 2016
I have exactly the same issue, DELETE fails on the preflight OPTIONS request. At the level of:
It is determined that no suitable handler was found for preflight OPTIONS preflight request and there should be 404 or 405 send as a response, but something is null and 500 is thrown instead.
And here it goes
return base.SelectAction(controllerContext);:Currently I have a workaround that redirects OPTIONS requests to my odata by adding an additional step in the pipeline before the controller is called, but it's ugly. Please fix this :)
lyweiwei commentedon Sep 1, 2016
How's it going on this issue? It has been opened for 1.5 year, and seems it still repros on the sample services.
bkwdesign commentedon Dec 21, 2017
I think I'm encountering a somewhat related issue when trying to escape special characters in my OData 'action'..
For example:
this request, which performs a search on 'fruit' works:
/odata/Search(searchterm = 'fruit')?$count=true&$expand=ThingType,Status,Locationthis request, which must be escaped, because I want to search 'A&D' fails:
/odata/Search(searchterm = 'A%26D')?$count=true&$expand=ThingType,Status,LocationFirefox console output says:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:64810/odata/Search(searchterm%20=%20'A%26D')?$count=true&$expand=ThingType,Status,Location,WorkOrderLinks($orderby=LinkAddedTime%20asc;$top=1). (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).When I look at the actual OPTIONS request, it says 400 Bad Request .. at first, I thought my jQuery ajax layer is interpreting the escaped characters when I don't want it to. But when I do an F11 step through of the code, that is not the case.
bitsforthought commentedon Sep 9, 2018
I've just independently encountered this issue (with a slightly different failure mode) when experimenting with the CORS implementation in Azure Search. Along the way, I've come up with a reliable repro and a possible workaround.
First, the repro. This is using Microsoft.AspNet.OData 7.0.1. There is a similar problem using Microsoft.AspNetCore.OData with CORS, but I filed a separate issue for that since the mechanics of CORS has changed quite a bit between ASP.NET and ASP.NET Core.
The repro can be found here
Here is the output from the failing test:
In this case, the failure isn't a nullref. Instead, the wrong path is taken through the action selection code, and the result is an
InvalidOperationExceptiondue to lack of sufficient information to disambiguate the two candidate actions (GetandDoSomething). As @LianwMS observed, this is because of the order of operations inAttributeBasedPolicyProviderFactory.GetCorsPolicyProvider. This method first copies all properties from the currentHttpRequestMessageto a newtargetRequest, then callsGetRouteDataon the original request.GetRouteDataadds new properties to the current request as a side effect, but not totargetRequest. This causes routing to fail.In my opinion this appears to be both a bug in the CORS implementation, and a design flaw in Web API OData:
GetRouteData.HttpRequestMessageproperties other thanRouteData. This appears to violate the intended design of ASP.NET routing.Fixing either would fix this problem, but given that the CORS implementation in classic ASP.NET is no longer being maintained, the only place left to fix this is in Web API OData. However, that would be a very expensive breaking change as it would touch potentially all routing-related code. I don't have enough information at this point to know whether fixing this for ASP.NET Core would be similarly expensive.
Fortunately, I may have stumbled across the beginnings of a potential workaround. Azure Search has been using a combination of Web API OData 5.9.1 and CORS for four years now, and we never ran into this issue because we install a message handler that calls
GetRouteDatabefore theCorsMessageHandleris called. This sets up all the necessary OData-related routing state beforeAttributeBasedPolicyProviderFactory.GetCorsPolicyProvideris called, which means it copies that state totargetRequest. This allows preflight requests to work.Unfortunately, this workaround doesn't work with Web API OData 7.0.1. due to a separate issue. Specifically, calling
GetRouteDatamore than once whereODataPathRouteConstraint.Matchsucceeds causesHttpRequestMessageExtensions.CreateRequestContainerto throw an exception. If we can fix that issue however, then callingGetRouteDataearly will continue to be a viable workaround for this CORS issue with classic ASP.NET.marabooy commentedon Oct 1, 2020
Closing this as a it is fixed now.