Access-Control-Allow-Origin 使用 Owin 时出错

Access-Control-Allow-Origin error when using Owin

我有一个 aurelia 客户端和一个网络服务器。当我使用 localhost 并且我在同一台机器上 运行 时,它工作正常。

但是当我想从另一台机器访问服务器时,页面加载但 api 调用给出以下错误: 请求的资源上不存在 Access-Control-Allow-Origin header。

我正在使用 owin,据我所知,我需要为 owin 启用 CORS。

我在我的创业公司class做了以下工作:-

更新 我已经使用 Nenad 的输入更新了我的 class,但仍然出现相同的错误。 下面我添加了来自客户端的调用。

 public void Configuration(IAppBuilder app)
        {

            this.container = new Container();
            // Create the container as usual.
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

            // Register your types, for instance using the scoped lifestyle:
            container.Register<IWebDeps, WebDeps>(Lifestyle.Singleton);

            // This is an extension method from the integration package.
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration, Assembly.GetExecutingAssembly());

            container.Verify();

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            // Configure Web API for self-host. 
            var config = new HttpConfiguration()
            {
                DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container)
            };

            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //// Custom Middleare
            app.Use(typeof(CustomMiddleware));
            app.UseWebApi(config);

            //New code:
            app.Run(context =>
            {
                context.Response.ContentType = "text/plain";
                return context.Response.WriteAsync("Hello, world.");
            });
        }   

我的主程序正在调用 startUp class:-

  using (Microsoft.Owin.Hosting.WebApp.Start<Startup>("http://localhost:8080"))
            {
                Console.WriteLine("Press [enter] to quit...");
                Console.ReadLine();
            }

客户端代码,192.168.178.23是服务器的ip。

let baseUrl2 = "http://192.168.178.23:8080/api/status/getStatus";
    getStatus() {
        return this.client.get(baseUrl2)
            .then(response => {
                return this.parseJSONToObject(response.content);
        });
    }

Chrome中的错误:

XMLHttpRequest cannot load http://192.168.178.23:8080/api/status/getStatus. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 400.

Cors 现在应该启用了吧?但是我在调​​用 api 时仍然收到错误。我缺少任何步骤吗?我们的这种方法错了吗?

欢迎提出任何建议!

您必须配置 WebAPI 才能使用 CORS。

  1. 安装 Nuget 包:

    Install-Package Microsoft.AspNet.WebApi.Cors
    
  2. HttpConfiguration 对象上启用 CORS:

    config.EnableCors();
    
  3. 在您的控制器上添加 [EnableCors] 属性:

    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.Cors;
    
    namespace WebService.Controllers
    {
        [EnableCors(origins: "www.example.com", headers: "*", methods: "*")]
        public class TestController : ApiController
        {
        // Controller methods not shown...
        }
    }
    

    或通过HttpConfig全局注册:

    var cors = new EnableCorsAttribute("www.example.com", "*", "*");
    config.EnableCors(cors);
    

更多详细信息:Enabling Cross-Origin Requests in ASP.NET Web API 2

添加这一行并检查,

 app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

并移除,

var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

这对我有用。

事实证明,当启动 OWIN 时,地址应该是 http://*:8080。而不是本地主机。