在我的 Web API 上启用 CORS 不起作用

Enable CORS on my Web API not working

我有以下网站API,自建:

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);

            }
        }
    }

只要我想启用 Cors,通过添加以下行,config.EnableCors(); 我的 Web API 就无法再通过 Swagger 访问,我得到以下响应:

<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>

我已经尝试设置 HttpConfiguration.EnsureInitialized(),但这会导致以下错误:

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.'

我安装了以下版本Microsoft.AspNet.WebApi.Cors

Install-Package Microsoft.AspNet.WebApi.Cors.cs -Version 5.2.3

如何在我的网站中启用 CORS api?

您忘记告诉 AppBuilder 使用 cors。

尝试在启动配置方法中添加以下行

app.UseCors(CorsOptions.AllowAll);

您可以通过以下示例启用corse

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;
    }
}

并在 WebApiConfig 的 app_start 中 将以下行放在方法 Register

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