I have the following Web API, self hoseted:
public class ApiShell : IApiShell { private IActorSystemSettings _settings; public ApiShell(IActorSystemSettings settings) { _settings = settings; } IDisposable _webApp; public void Start() { _webApp = WebApp.Start<Startup>(_settings.SystemUrl); Console.WriteLine($"Web server running at '{_settings.SystemUrl}'"); } public void Stop() { _webApp.Dispose(); } internal class Startup { //Configure Web API for Self-Host public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.EnableCors(); config.MapHttpAttributeRoutes(); //default route config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); config .EnableSwagger(c => c.SingleApiVersion("v1", "Web API")) .EnableSwaggerUi(); app.UseWebApi(config); config.DependencyResolver = new AutofacWebApiDependencyResolver(IoC.Container); } } } As soon as I would like to Enable Cors, by adding the following line, config.EnableCors(); my Web API is not reachable through Swagger anymore and I get the following reponse:
<Error> <Message>An error has occurred.</Message> <ExceptionMessage> The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code. </ExceptionMessage> <ExceptionType>System.InvalidOperationException</ExceptionType> <StackTrace> at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.HttpRouteCollection.GetRouteData(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.HttpServer.<SendAsync>d__24.MoveNext() </StackTrace> </Error> I have tried setting the HttpConfiguration.EnsureInitialized(), but this results in the following error:
Could not load file or assembly 'System.Web.Cors, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.'
I have installed the following version of Microsoft.AspNet.WebApi.Cors
Install-Package Microsoft.AspNet.WebApi.Cors.cs -Version 5.2.3
How can I enable CORS in my web api?