简体   繁体   中英

Net Core Cors and Angular application on IIS

I'm having some troubles setting up the correct Cors settings on my application. NetCore application with Angular6 hosted on IIS , the angular app is outside the .Net project and compiled and inserted inside the wwwroot when publishing.

Now the problem is that when I'm coding the angular part, I'd like to call directly the release server to test some functionality. I tried any kind of approach to have this work out but it seems like I'm always hitting a problem with the Cors setup but only for the POST calls, GET works fine. So here is my startup code:

// 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);
    });
}

Since I want this enabled only for development purpose I'd like to enable it globally.

i think you need to set the origin manually

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

as shown in here

将 cors 添加到启动 asp.net core web API

This's the necessary part to add cors in your web API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM