首页 > 解决方案 > 带有 Javascript 的 Dot Net Core Web API - CORS 策略错误

问题描述

我正在将 Visual Studio 代码与 liveserver 一起用于 html/javascript,并将 VS Studio 2019 用于 Dot net core Web API 我已经在本地 Windows 10 的 IIS 中为 Web api 创建了站点。

  1. 我有一个登录页面,它接受用户名和密码。这是在 login.html 中编码的

登录页面具有以下 javascript 函数,即在登录按钮单击事件时调用

function fnlogin() {
   window.location.href = "http://localhost:5500/productmenu.html"
}
  1. 登录后,将显示一个菜单页面。这是在 productmenu.html 中编码的,带有以下内容
<header>
   <ul class = "nav">
     <li class="navlink"> <a href="productInfo.html> target="content"> Product Information <a> <li?
     <li class="navlink"> <a href="orderHistory.html> target="content"> Order History <a> <li?
   </ul>
</header>
  1. 一旦用户选择菜单选项“产品信息”,就会显示另一个 html 页面。这在 productinfo.html 中编码

  2. 一旦用户输入产品代码并点击搜索,就会调用 dot net core web api 并使用 fetch api 在 productinfo.html 中显示数据。

该api在JS中调用如下

fetch('http://localhost:8082/api/product/' + productId)
.then(response => response(json))
.then((response => {
    return response
})
.then ( (response) => {
    console.log(response);
   })
.catch(err => console.log(err));
  1. dot net core web api 在 startup.cs 中有以下内容
method : configureServices

services.AddDefaultPolicy(
   options.AddDefaultPolicy (
      builder => 
      {
           builder.WithOrigins("http://127.0.0.1:5500)
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()
      })
)};

配置方法有以下

app.UseRouting();
app.UseCors();
app.UseAuthorization():

Web api 发布在 IIS 站点中,端口为 8082

问题如下

  1. 当我直接在浏览器中测试 web api 时,它可以正常工作
  2. 当我在实时服务器中运行 productmenu.html 时,会打开一个新的浏览器窗口,其中包含链接 127.0.0.1:5500/productmenu.html 并显示菜单。选择“产品信息”菜单选项后,将显示页面产品信息页面。输入产品 ID 并单击搜索按钮后,将调用 Web api,然后正确显示产品信息。没有任何问题..
  3. 但是,当我在 VS 代码/实时服务器中运行 login.html,并使用相同的步骤(如 #2 中所述)导航到产品信息页面并单击搜索按钮时,我在 Chrome 开发工具中收到以下 CORS 错误“访问 .. from origin ... 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。”

我检查了 Chrome 开发工具中的网络选项卡并查看请求标头

Accept: */*
Host: localhost:8082
Origin: http://localhost:5500
Sec-Fetch-Dest: Empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site : same-site

标签: javascriptc#asp.net-coreasp.net-web-api.net-core

解决方案


你在 Cors 语法中有一个错误。这是默认策略的语法:

 services.AddCors(options =>
        {
       options.AddDefaultPolicy(
         builder => 
      {
           builder.WithOrigins("http://127.0.0.1:5500")
            .AllowAnyHeader()
            .AllowAnyMethod();
             });
        });

但如果仍然无法正常工作,您可以尝试将默认 Cors 策略替换为命名策略


public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("AllowOrigins", builder =>
            {
                builder.WithOrigins("http://localhost:5500")
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

        .....
            
        }

        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            .....

            app.UseRouting();
            app.UseCors("AllowOrigins");
           app.UseAuthorization();

            ....
         }

推荐阅读