asp.net core 系列之允许跨域访问2之测试跨域(Enable Cross-Origin Requests:CORS)

 

这一节主要讲如何测试跨域问题

 

你可以直接在官网下载示例代码,也可以自己写,我这里直接使用官网样例进行演示

样例代码下载:

Cors

 

一.提供服务方,这里使用的是API

1.创建一个API项目。或者直接下载样例代码

2.像之前讲的那样设置允许CORS,例如:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    // Shows UseCors with CorsPolicyBuilder.
    app.UseCors(builder =>
    {
        builder.WithOrigins("http://example.com",
                            "http://www.contoso.com",
                            "https://localhost:44375",
                            "https://localhost:5001");
    });

    app.UseHttpsRedirection();
    app.UseMvc();
}

 

使用的时候,注意 WithOrigins("https://localhost:<port>"); 这个地址替换为客户端地址(即调用方:这里指部分Razor代码)

 

二.客户端,这里指调用方(页面中js调用),这里指Razor部分的代码

1.创建一个web 应用(Razor pages 或者 mvc )。样例用的Razor Pages 。

2.在index.cshtml中增加如下代码

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">CORS Test</h1>
</div>

<div>
    <input type="button" value="Test" 
           onclick="requestVal('https://<web app>.azurewebsites.net/api/values')" />
    <span id='result'></span>
</div>

<script>
    function requestVal(uri) {
        const resultSpan = document.getElementById('result');

        fetch(uri)
            .then(response => response.json())
            .then(data => resultSpan.innerText = data)
            .catch(error => resultSpan.innerText = 'See F12 Console for error');
    }
</script>

 


 

这里再多说一下,我的操作流程

首先,下载样例代码;

然后,在同一个解决方案中,导入Cors样例代码,如图

然后,可以先把解决方案设置为多个启动项目,启动,看下ClientApp的URL和WebAPI的URL

 

 

 

得到,我的url 分别如下:

ClientApp
http://localhost:65317/

WebApi
http://localhost:65328/

 

 先停止运行,分别设置api的withOrigin和client页面中的地址,代码如下:

WebAPI中的 StartupTest (这个跟Program使用的StartUp文件有关,样例代码中使用的StartUpTest)

// Shows UseCors with CorsPolicyBuilder.
            app.UseCors(builder =>
            {
                builder.WithOrigins("http://example.com",
                                    "http://www.contoso.com",
                                    "https://localhost:44375",
                                    "http://localhost:65317");
            });

ClientApp中的Index.cshtml文件代码如下:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">CORS Test</h1>
</div>

<div>
    <h3>Test results:</h3>
    <span id='result'></span>
</div>

<div>
    <input type="button" value="Test Widget 1"
           onclick="requestVal('https://webapi123.azurewebsites.net/api/widget/1')" />
    <input type="button" value="Test All Widgets"
           onclick="requestJson('https://webapi123.azurewebsites.net/api/widget')" />
    <input type="button" value="Test All Val"
           onclick="requestJson('https://webapi123.azurewebsites.net/api/values')" />
    <input type="button" value="Test Val 1"
           onclick="requestVal2('https://webapi123.azurewebsites.net/api/values/1')" />
    <input type="button" value="Test Val 2"
           onclick="requestVal2('http://localhost:65328/api/values')" />
    <input type="button" value="Test Val 3"
           onclick="requestJson('http://localhost:65328/api/values')" />
</div>

<script>
    function requestJson(uri) {
        const resultSpan = document.getElementById('result');

        fetch(uri)
            .then(response => response.json())
            .then(data => resultSpan.innerText = data)
            .catch(error => resultSpan.innerText = 'See F12 Console for error');
    }
</script>

<script>
    function requestVal2(uri) {
        const resultSpan = document.getElementById('result');

        fetch(uri)
            .then(response => response.text())
            .then(data => resultSpan.innerText = data)
            .catch(error => resultSpan.innerText = 'See F12 Console for error');
    }
</script>

 

再运行,测试

发现当WebApi中的 WithOrigins 设置正确时,不会报跨域问题,

否则,报跨域问题。

跨域错误截图

 

 

 如有疑问,可以参考网址:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#cors-policy-options

posted @ 2019-05-02 03:40  Vincent-yuan  阅读(1116)  评论(0编辑  收藏  举报