The code for this post is published in the MSDN Code Gallery.
A few months back I had posted some code to enable support for CORS (Cross-Origin Resource Sharing) in the ASP.NET Web API. At that point, that product was in its Beta version, and with the Release Candidate (RC) released last month, some of the API changes made the code stop working (and in the per-action example, it even stopped building). With many comments asking for an updated version which builds, here they are.
The first version (a global message handler, which enabled CORS for all controllers / actions in the application), actually didn’t need any update at all. Actually, the message handler didn’t need any updates, but the actions in the values controller which take the string as a parameter need a [FromBody] decoration due to the model binding changes between the Beta and the RC version. In RC, parameters of simple types (such as string) by default come from the URI (either in the route or in the query string), and the application passed the parameter via the request body.
The second version – CORS support on a per-action basis – had some changes. That version was implemented using two components: one filter attribute, and one action selector (to define the action that would respond to preflight requests). The code for the filter was almost the same, with the exception that the property of the HttpActionExecutedContext in the action filter which stored the response changed from Result to Response:
The code for the action selector itself was actually unchanged, but the nested type to implement the new action descriptor had quite a lot of changes, mostly related to the OM changes in the HttpActionDescriptor class (related to return types). Besides trivial changes (e.g., from ReadOnlyCollection<T> to Collection<T>), there were two larger changes:
And that’s basically it. The code in the gallery will contain both projects (global CORS + per-action CORS), along with a simple project which can be tested (in CORS-enabled browsers, such as Chrome, IE10+ and FF3.5+) for both services.
[Code from this post]