发布到 IIS 后启用 CORS 不起作用

2024-02-21

我将 dotnet core 2.2 Web api 应用程序托管到本地 IIS。当我运行托管网站时,网站正在运行。我正在尝试从角度登录,但它不起作用。

It says 从源“http://localhost:4200”访问位于“http://192.168.43.143:100/Auth/Login”的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头关于所请求的资源。

Note: 它在本地工作。没有发生 CORS 策略问题

我在ConfigureServices中添加了cors策略,并提供了中间件来添加UseCors()。

public void ConfigureServices(IServiceCollection services)
{
   services.AddCors(c =>  
            {    
                c.AddPolicy("AllowOrigin", options => options.AllowAnyHeader()
                    .AllowAnyMethod().AllowAnyOrigin()
                    .SetIsOriginAllowed((host) => true).AllowCredentials());  
            });

   services.Configure<MvcOptions>(options => {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowOrigin"));
            });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("AllowOrigin");
    app.UseMvc();
}

我安装的软件详细信息如下,

  • 系统:Windows 10
  • DotNet 核心 SDK:2.2.110 和 3.1.201
  • Windows 服务器托管:2.2.1

下面给出基本代码供您参考。

点网核心Web API:

程序.cs

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://localhost:4000")
                .UseStartup<Startup>();
    }

启动.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin",
                    options => options.WithOrigins("*").AllowCredentials().AllowAnyHeader().AllowAnyMethod()
                );
            });

            // DbContext and JWT implementation done

            // Authorization filter added
            
            services.Configure<MvcOptions>(options => {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowOrigin"));
            });

            //Dependence Injunction done
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // app.UseForwardedHeaders();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseAuthentication();  //it is used to authorize jwt tokens
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseHttpsRedirection();
            app.UseCors();
            app.UseMvc();
        }

托管Web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\TestAPI.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
    </system.webServer>
  </location>
</configuration>
<!--ProjectGuid: 9aea96ef-cfc4-4231-9bfb-78f4efec933f-->

启动设置.json:

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:4000",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      //"launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "TestAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:4000/values",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

角7:

给出了拦截器代码

const authReq = this.currentuser
      ? request.clone({
        headers: request.headers.set('Authorization', 'Bearer ' + this.currentuser)
          .set('Access-Control-Allow-Origin', '*')
          .set('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
          .set('Content-Type', request.headers.get('content-type') ?
            request.headers.get('content-type') : 'application/json')
      })
      : request.clone({
        headers: request.headers
        .set('Access-Control-Allow-Origin', '*')
          .set('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
          .set('Content-Type', 'application/json')
      });
    return next.handle(authReq).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          // auto logout if 401 response returned from api
          this.authenticationService.logout();
          // tslint:disable-next-line: deprecation
          location.reload(true);
        }
        return throwError(error);
      }));

IIS Configuration image given below enter image description here


我必须将 CORS 策略移至 web.config 文件中以供 IIS 管理。

当由反向代理 IIS 托管时,我根本无法说服 AddCors 工作。

经过大量(日复一日)的反复试验后,我求助于让 IIS 来管理它。这意味着如果我需要分离我的 ASP.NET (Net5.0) 应用程序,我必须在两个地方配置 CORS(至少不是同时),但我怀疑这种情况是否会发生(著名的遗言。 ..)

我忍不住想知道这是否是设计使然——如果 IIS 故意禁用 Kestrel 中的 CORS 处理?如果您考虑一下,OPTIONS 方法会到达 IIS 公共端点,被中继到 .NET Core 托管应用程序,并在响应中传回 go/no-go。这构成每次发出请求时的两步调用。现在,如果在第一层处理,可以减少大量的中继。

我希望这能在某种程度上有所帮助,即使不是至少可以安慰你,让你知道你并不孤单。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

发布到 IIS 后启用 CORS 不起作用 的相关文章

随机推荐