【问题标题】:aspnetcore 2.2 api CORS policyaspnetcore 2.2 api CORS 策略
【发布时间】:2019-01-08 21:27:32
【问题描述】:

我已将 netcoreapp 从 2.1 更新到 2.2,但无法弄清楚如何让 CORS 再次工作。之前使用过如下配置:

            services.AddCors(o => o.AddPolicy("App", builder =>
            builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()

升级到 2.2 后,.AllowAnyOrigin() 不再受支持。我已将配置更改为:

        services.AddCors(o => o.AddPolicy("App", builder =>
            builder
                .WithOrigins("http://localhost:8080", "ionic://localhost", "http://localhost") // (development, cordova-ios, cordova-android)
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
        ));
    }

我也在使用 https://github.com/ionic-team/cordova-plugin-ionic-webview 插件 for cordova。 android和ios的Webview来源如下:http://localhost, ionic://localhost

我在 Android 上收到以下错误:

Access to XMLHttpRequest at 'https://my-host-app.azurewebsites.net/api/user/profile' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested 

请求标头:

:authority: my-host-app.azurewebsites.net
:method: OPTIONS
:path: /api/user/profile
:scheme: https
accept: */*
accept-encoding: gzip, deflate
accept-language: en-US,ru-RU;q=0.9
access-control-request-headers: api-version,deviceid,isapp
access-control-request-method: GET
origin: http://localhost
referer: http://localhost/
user-agent: Mozilla/5.0 (Linux; Android 8.0.0; ONEPLUS A3003 Build/OPR1.170623.032; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.99 Mobile Safari/537.36
x-requested-with: com.company.my-app

响应标头:

access-control-allow-credentials: true
access-control-allow-headers: api-version,deviceid,isapp
access-control-allow-methods: GET
access-control-allow-origin: http://localhost
date: Tue, 08 Jan 2019 11:52:54 GMT
request-context: appId=cid-v1:d20ad272-fa9b-4051-a89a-eea17ae49380
server: Kestrel
set-cookie: ARRAffinity=2252b451f5ef07b7d0d5027457bd2b71e73fb479db2cf5924161a51c2ec7b5;Path=/;HttpOnly;Domain=my-host-app.azurewebsites.net
status: 204
strict-transport-security: max-age=2592000
vary: Origin
x-powered-by: ASP.NET

在 iPhone 上相同,但使用 ionic://localhost。

【问题讨论】:

    标签: .net cordova .net-core


    【解决方案1】:

    我通过将.WithOrigins() 替换为.SetIsOriginAllowed((host) => true) 解决了问题。

    【讨论】:

    • 谁能解释这两种方法的区别?为什么会有帮助?
    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 2021-10-15
    • 2021-06-22
    • 2015-11-14
    • 1970-01-01
    • 2021-07-20
    • 2021-11-13
    • 2023-03-13
    相关资源
    最近更新 更多