-1

I am getting the following error for PUT request. Gets are working fine.

Access to fetch at from origin has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response. c# .net core

The api startup class looks fine as follows. Not sure what I am missing.

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<AppDbContext>(options => options.UseInMemoryDatabase(databaseName: "BethanysPieShopHRM"));

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

        services.AddScoped<ICountryRepository, CountryRepository>();
        services.AddScoped<IJobCategoryRepository, JobCategoryRepository>();
        services.AddScoped<IEmployeeRepository, EmployeeRepository>();

        services.AddCors(options =>
        {
            options.AddPolicy("Open", builder => builder.AllowAnyOrigin().AllowAnyHeader());
        });

        services.AddControllers();
            //.AddJsonOptions(options => options.JsonSerializerOptions.ca);
    }

    // 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.UseAuthorization();

        app.UseCors("Open");

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
Phil
  • 157,677
  • 23
  • 242
  • 245
VivekDev
  • 20,868
  • 27
  • 132
  • 202
  • 1
    Does this answer your question? [How to enable CORS in ASP.NET Core](https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core). Pay particular attention to the `AllowAnyMethod()` call – Phil Oct 15 '21 at 02:27
  • Yes, Thanks. This helped. – VivekDev Oct 15 '21 at 02:33
  • All that I needed to do was to add the attribute [EnableCors("Open")] to my HttpPut method. – VivekDev Oct 15 '21 at 04:01

1 Answers1

0

You put Cors code in a wrong place.

Try to move UseCors between UseRouting and UseAuthorization

app.UseRouting();
 app.UseCors("Open");
 app.UseAuthorization();

and move AddCors to the top of method.

Serge
  • 40,935
  • 4
  • 18
  • 45