gpt4 book ai didi

.net-core - 发布到 IIS 后启用 CORS 不起作用

转载 作者:行者123 更新时间:2023-12-04 11:32:51 26 4
gpt4 key购买 nike

我将 dotnet core 2.2 web api 应用程序托管到本地 IIS。当我运行托管站点时,站点正在运行。我正在尝试从 angular 登录,但它不起作用。
它说 CORS 策略阻止了来自源“http://localhost:4200”的“http://192.168.43.143:100/Auth/Login”处对 XMLHttpRequest 的访问:不存在“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();
}
我安装的软件详细信息如下,
  • 系统: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>();
    }
    启动文件
    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 配置图像
    enter image description here

    最佳答案

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

    Access to XMLHttpRequest at 'http://192.168.43.143:100/Auth/Login'


    据我所知, Asp.Net Core WebAPI2.2默认使用 https 重定向,这可能是问题的原因。
      app.UseHttpsRedirection();
    //app.UseCors("AllowOrigin");
    app.UseMvc();
    此外,我建议您尝试另一种方法来解决 CORS 问题。
    https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors
    例如下面的方式,我们用 EnableCors 属性装饰 Values Controller 以支持 CORS。
    值 Controller 。
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("MyPolicy")]
    public class ValuesController : ControllerBase
    {
    Startup.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();
    }
    最后,如果我们在IIS中开启了其他认证方式,比如windows认证,最好安装 IIS Cors module支持 CORS。这也很有帮助。
    https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
    如果问题仍然存在,请随时告诉我。

    关于.net-core - 发布到 IIS 后启用 CORS 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62861287/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com