IIS 上的 Net Core Cors 和 Angular 应用程序

Posted

技术标签:

【中文标题】IIS 上的 Net Core Cors 和 Angular 应用程序【英文标题】:Net Core Cors and Angular application on IIS 【发布时间】:2019-04-02 12:05:14 【问题描述】:

在我的应用程序上设置正确的 Cors 设置时遇到了一些问题。 NetCore 应用程序与 Angular6 托管在 IIS 上,angular 应用程序位于 .Net 项目之外,并在发布时编译并插入到 wwwroot 内。

现在的问题是,当我编写angular 部分时,我想直接调用发布服务器来测试一些功能。 我尝试了任何一种方法来解决这个问题,但似乎我总是遇到 Cors 设置的问题,但仅适用于 POST 调用,GET 工作正常。所以这是我的启动代码:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)

    services.AddSingleton<ILoggerManager, LoggerManager>();
    services.AddSingleton<IDbContext, MongoDbContext>();
    services.AddSingleton<IIdGenerator, IdGenerator>();
    services.AddSwaggerGen(c =>
    
        c.SwaggerDoc("v1", new Info  Title = "My API", Version = "v1" );
        c.AddSecurityDefinition("Bearer", new ApiKeyScheme()In = "header",Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey");
        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
        
            "Bearer", Enumerable.Empty<string>()
        );
    );
    services.AddCustomRepositories();
    services.AddCustomServices();
    services.AddJwtService();

    //Add cors
    services.AddCors();

    // Add framework services.
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.Configure<IISOptions>(options =>
    
        options.ForwardClientCertificate = false;
    );
    services.Configure<Settings>(Configuration.GetSection("SystemSettings"));


// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    //app.UseCors("AllowSpecificOrigin");

    if (env.IsDevelopment())
    
        app.UseDeveloperExceptionPage();
    
    else
    
        app.UseHsts();
    

    app.UseCors(builder => builder
        .AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod());

    app.UseDefaultFiles();

    // this will serve js, css, images etc.
    app.UseStaticFiles();
    app.Use(async (context, next) =>
    
        if (context.Request.Path.HasValue && 
            !context.Request.Path.Value.StartsWith("/api/") &&
            !context.Request.Path.Value.StartsWith("/swagger"))
        
            context.Response.ContentType = "text/html";
            await context.Response.SendFileAsync(
                env.ContentRootFileProvider.GetFileInfo("wwwroot/index.html")
            );
            return;
        
        await next();
    );

    //app.UseHttpsRedirection();
    app.UseSwagger();
    app.UseAuthentication();
    app.UseMiddleware(typeof(ErrorHandlingMiddleware));

    app.UseMvc();  

    app.UseSwaggerUI(c =>
    
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.DocExpansion(DocExpansion.None);
    );

由于我希望仅出于开发目的启用此功能,因此我想在全球范围内启用它。

【问题讨论】:

@KirkLarkin 无法加载 xxx:8080/api/users:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'localhost:4200' 不允许访问。响应的 HTTP 状态代码为 500。 好的,很好 - 这正是我所期待的。请注意最后一行:响应具有 HTTP 状态代码 500。这意味着您的服务器正在抛出异常,而 是您应该查看的内容。 我以为 500 是针对 Cors 问题的... 不,不正常。检查您的调试器、日志记录等,以查看在您的 ASP.NET Core 项目中引发异常的位置。在当前版本的 ASP.NET Core 中,发生错误时不会设置 CORS 标头。 似乎我在程序中没有记录某种异常,我现在正在尝试调试它,但我认为这可能是现在的问题 【参考方案1】:

我认为你需要手动设置原点

app.UseCors(builder =>
            builder.AllowAnyOrigin().AllowAnyMethod());

如图in here

【讨论】:

从源“localhost:4200”访问“XXX/api/users”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。与以前几乎相同的错误,但使用“AllowAnyOrigin”应该不需要 尝试设置 .AllowAllHeaders() 是的,我只是将 AllowAnyOrigin 更改为特定的,我尝试使用此设置: app.UseCors(builder => builder .WithOrigins("localhost:4200") .AllowAnyHeader() .AllowAnyMethod ()); 尝试 AllowAnyOrigins() AllowAnyOrigin 是我在主要示例中使用的【参考方案2】:

这是在您的 Web API 中添加 cors 的必要部分。

【讨论】:

请勿将代码分享为图片。请使用 *** 的code formatting tools

以上是关于IIS 上的 Net Core Cors 和 Angular 应用程序的主要内容,如果未能解决你的问题,请参考以下文章

PUT 请求抛出 403 CORS 错误 Asp.Net Core 3.1 + Vue3 +IIS10

仅在 IIS 中发布时,在 ASP.net Core 3.1 WebAPI 中启用 CORS 时出错

asp.net core发布到iis后出现An error occurred while starting the application

Asp.NET Core 在IIS部署 An assembly specified in the application dependencies manifest was not found(示例代

[转].Net Core Web应用发布至IIS后报“An error occurred while starting the application”错误

.NET Core CORS 策略块