0

I have an api with asp core 3.1 when I use local host every thing is fine, but when I publish it on my IIS it not work and give me error for enabling CORS

my startup.cs code is

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

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



        services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer(
            this.Configuration.GetConnectionString("DefaultConnection")));

        //Configure Identity framework core  
        services.AddIdentityCore<ApplicationUser>()
             .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();



        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.Password.RequiredLength = 4;
            config.Password.RequireDigit = false;
            config.Password.RequireNonAlphanumeric = false;
            config.Password.RequireUppercase = false;
            config.Password.RequireLowercase = false;
        })
           .AddEntityFrameworkStores<ApplicationDbContext>()
           .AddDefaultTokenProviders();




        services.AddCors(options =>
        {
            options.AddPolicy("CrosPolicy", builder =>
            builder
            .SetIsOriginAllowed((host) => true)
            //.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()
            .Build()
            );
        });
        services.AddControllers();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
           {
               options.TokenValidationParameters = new TokenValidationParameters
               {
                   ValidateIssuer = true,
                   ValidateAudience = true,
                   ValidateLifetime = true,
                   ValidateIssuerSigningKey = true,
                   ValidIssuer = Configuration["jwt:Issuer"],
                   ValidAudience = Configuration["jwt:Issuer"],
                   IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["jwt:key"]))
               };
           });            

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CrosPolicy");

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

I dont know what I have to do plz help me , also I try solutions in this post, How to enable CORS in ASP.net Core WebAPI it not work for me

enter image description here

Zoha Shobbar
  • 446
  • 8
  • 17
  • https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module – Lex Li Jun 02 '20 at 16:03
  • I suggest you could aslo check you have enabled any IIS Authentication mode. For example "Basic Authentication". If you have enabled any IIS Authentication, I suggest you could try to modify it to `Anonymous authentication` to check if this error is disapperared. – Brando Zhang Jun 03 '20 at 02:08

1 Answers1

0

i tried a lot of things but at the end i found the solution ,i changed the place of CORS like this :

 public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {



        services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer(
            this.Configuration.GetConnectionString("DefaultConnection")));


        services.AddIdentityCore<ApplicationUser>()
             .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();



        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.Password.RequiredLength = 4;
            config.Password.RequireDigit = false;
            config.Password.RequireNonAlphanumeric = false;
            config.Password.RequireUppercase = false;
            config.Password.RequireLowercase = false;
        })
           .AddEntityFrameworkStores<ApplicationDbContext>()
           .AddDefaultTokenProviders();




        services.AddControllers();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
           {
               options.TokenValidationParameters = new TokenValidationParameters
               {
                   ValidateIssuer = true,
                   ValidateAudience = true,
                   ValidateLifetime = true,
                   ValidateIssuerSigningKey = true,
                   ValidIssuer = Configuration["jwt:Issuer"],
                   ValidAudience = Configuration["jwt:Issuer"],
                   IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["jwt:key"]))
               };
           });


        services.AddMvc();

    }


    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

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

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
Zoha Shobbar
  • 446
  • 8
  • 17