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

Ven*_*n R 7 .net-core iis-10 asp.net-core-webapi

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

它说访问 XMLHttpRequest at 'http://192.168.43.143:100/Auth/Login' from origin 'http://localhost:4200' has been Blocked by CORS policy: No 'Access-Control-Allow-Origin' header存在于请求的资源上。

注意:它在本地工作。没有发生 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();
}
Run Code Online (Sandbox Code Playgroud)

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

  • 系统:Windows 10
  • 点网核心 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>();
    }
Run Code Online (Sandbox Code Playgroud)

启动文件

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();
        }
Run Code Online (Sandbox Code Playgroud)

托管 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-->
Run Code Online (Sandbox Code Playgroud)

启动设置.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"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

角 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);
      }));
Run Code Online (Sandbox Code Playgroud)

下面给出的 IIS 配置图像 在此处输入图片说明

Abr*_*ian 1

我测试了你解决 CORS 问题的代码片段,它在我这边工作得很好。我唯一的问题是为什么默认请求发送到 HTTP 方案,而不是 HTTPS 服务端点。

访问“http://192.168.43.143:100/Auth/Login”处的 XMLHttpRequest

据我所知,Asp.Net Core WebAPI2.2默认使用https重定向,这可能是问题的原因。

  app.UseHttpsRedirection();
            //app.UseCors("AllowOrigin");
            app.UseMvc();
Run Code Online (Sandbox Code Playgroud)

另外,我建议您尝试其他方法来解决CORS问题。
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors
比如下面的方式,我们用EnableCors属性装饰Values控制器来支持CORS。
值控制器。

[Route("api/[controller]")]
    [ApiController]
    [EnableCors("MyPolicy")]
    public class ValuesController : ControllerBase
    {
Run Code Online (Sandbox Code Playgroud)

启动.cs

        public void ConfigureServices(IServiceCollection services)
        {
           services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddCors(options =>
            {
                options.AddPolicy("MyPolicy", builder =>
                 {
builder.WithOrigins("*").AllowCredentials().AllowAnyHeader().AllowAnyMethod();
                 });
            });
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
     
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseCors();

            app.UseMvc();
        }
Run Code Online (Sandbox Code Playgroud)

最后,如果我们在IIS中启用了其他身份验证模式,例如Windows身份验证,我们最好安装IIS Cors module支持CORS。这也很有帮助。
https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
如果问题仍然存在,请随时告诉我。