Search code examples
c#asp.net-web-api2odata

Get CORS preflight request to follow ODATA routing


I'm using Microsoft.AspNet.WebApi.Cors to enable cross origin request for certain actions on certain controllers (both WebApi & OData) using the [EnableCors(...)] attribute.

This works fine for all the WebApi requests and most OData, but on a particular controller we have two POST actions that are given different routes by the [ODataRoute(...)], and the preflight request for either of those actions is returned a 500 error saying that 'Multiple actions were found that match the request. It looks like CORS doesn't know to look for the OData routing.

Has anyone else experienced this problem and come up with a solution?

Here is the route config:

// Web API routes
config.MapHttpAttributeRoutes();

config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: null,
    model: _GetModel());

// Web API configuration and services
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );

And here is the controller with the duplicate actions:

[EnableCors("*", "*", "*")]
[ODataRoute("Action-1")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}

[EnableCors("*", "*", "*")]
[ODataRoute("Action-2")]
[HttpPost]
public async Task<IHttpActionResult> Action(ODataActionParameters parameters, ODataQueryOptions<Guid> options)
{
    ...
}

Solution

  • In the end I just went with Microsoft.Owin.Cors instead, and hard coded a list of paths that I wanted to enable CORS on for the PolicyResolver.

    It's not ideal doing it this way, but I think it's going to take an unreasonable amount of time to work out how to get this working properly.