简体   繁体   中英

Enable CORS on my Web API not working

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?

You forgot to tell the AppBuilder to use cors.

Try and add the following line in the Startup Configuration method

app.UseCors(CorsOptions.AllowAll);

you can enable corse by the following sample

using System.Web.Http;
using System.Web.Http.Cors;

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EvalSamplesController : ApiController
{
    [HttpGet]
    public List<EvalSamplesViewModel> GetHeaderList()
    {
        List<EvalSamplesViewModel> simpleModel = obj.ReadAllList();
        return simpleModel;
    }
}

and in the app_start in WebApiConfig put the following line in the method Register

public static void Register(HttpConfiguration config)
    {
      config.EnableCors();
     ///////// 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM