【问题标题】:Access-Control-Allow-Origin error when using Owin使用 Owin 时出现 Access-Control-Allow-Origin 错误
【发布时间】:2017-12-29 00:08:51
【问题描述】:

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

但是当我想从另一台机器访问服务器时,页面会加载,但 api 调用会出现以下错误: 请求的资源上没有 Access-Control-Allow-Origin 标头。

我正在使用 owin,但我不明白我需要为 owin 启用 CORS。

我在我的创业课上做了以下事情:-

更新 我已经用 Nenad 的输入更新了我的课程,但仍然遇到同样的错误。 下面我添加了来自客户端的调用。

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

  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 无法加载 http://192.168.178.23:8080/api/status/getStatus。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:9000” 使用权。响应的 HTTP 状态代码为 400。

现在应该启用 Cors 吧?但是在进行 api 调用时我仍然会收到错误消息。我错过了任何步骤吗?我们的这种方法错了吗?

欢迎提出任何建议!

【问题讨论】:

  • 我会尝试添加行app.UseWebApi(config);,也许需要将具有CORS设置的appconfig中的路由相关联。

标签: asp.net .net owin aurelia


【解决方案1】:

您必须配置 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

【讨论】:

  • 谢谢你的回答,。我现在就试试这个。这在您使用 OWIN 时有效吗?
  • 嗨 Nenad,我已经尝试过你的解决方案,但我遇到了同样的错误。我已添加 api 调用的客户端代码以获取更多信息。
【解决方案2】:

添加这一行并检查,

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

并删除,

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

这对我有用。

【讨论】:

  • 您好,感谢您的评论。我试过了,但仍然没有结果
【解决方案3】:

原来在启动 OWIN 时,地址应该是 http://*:8080。而不是本地主机。

【讨论】:

    猜你喜欢
    • 2017-06-15
    • 1970-01-01
    • 2023-03-15
    • 2013-04-26
    • 2018-01-26
    • 2015-06-05
    • 2018-12-12
    • 2012-05-08
    • 1970-01-01
    相关资源
    最近更新 更多