locked
Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. RRS feed

  • Question

  • User2041008840 posted

    Hello, 
    I can fetch data from api but i cant post/insert data. my project in blazor webassebly and asp.net core web api. 

    errror : blocked by Cors Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. I also add cors policy but still its not working
    here is my code 

    create.razor page
    
    @page "/customers"
    <h3>Customers</h3>
    
    @inject CustomersService CustomersService
    
    @if (customers == null)
    { }
    else
    { 
    @foreach (var item in customers)
    {
        @item.Name
    }
    }
    <EditForm Model="@customer" OnValidSubmit="@Insert">
        <input @bind="@customer.Name" class="form-control" id="txtName" />
        <input type="submit" class="btn btn-default" value="Submit" />
    </EditForm>
    
    @code {
        Customer customer = new Customer();
        Customer[] customers;
        protected override async Task OnInitializedAsync()
        {
            customers =  await CustomersService.GetCustomersJsonAsync();
        }
        protected async Task Insert()
        {
            customer.SetupID = 1;
            await CustomersService.InsertCustomersAsync(customer);
        }
    }
    

    CustomersService.cs

       readonly string baseUrl = "https://localhost:44341/";
    
     public async Task<Customer[]> GetCustomersAsync()
            {
                HttpClient http = new HttpClient();
                var json = await http.GetStringAsync($"{baseUrl}api/Customers");
                return JsonConvert.DeserializeObject<Customer[]>(json);
            }
            public async Task<Customer[]> GetCustomersJsonAsync()
            {
                HttpClient http = new HttpClient();
                var json = await http.GetJsonAsync<Customer[]>($"{baseUrl}api/Customers");
                return json;
            }
    public async Task<HttpResponseMessage> InsertCustomersAsync(Customer Customers)
            {
                var client = new HttpClient();
                return await client.PostAsync($"{baseUrl}api/Customers", GetStringContentFromObject(Customers));
            }
            
            public async Task InsertCustomersJsonAsync(Customer Customers)
            {
                HttpClient client = new HttpClient();
                await client.PostJsonAsync($"{baseUrl}api/Customers", Customers);
            }
     private StringContent GetStringContentFromObject(object obj)
            {
                var serialized = JsonConvert.SerializeObject(obj);
                var stringContent = new StringContent(serialized, Encoding.UTF8, "application/json");
                return stringContent;
            }

    Customer.cs

       public class Customer
        {
            public int ID { get; set; }
            [Required]
            public string Name { get; set; }
            public int SetupID { get; set; }
            public virtual Setup Setup { get; set; }
        }

    Startup.cs in web api

     public class Startup
        {
            readonly string MyPolicy = "_myPolicy";
            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.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
    
                services.AddControllers();
    
                services.AddCors(options =>
                {
                    options.AddPolicy(name: MyPolicy,
                        builder =>
                        {
                            builder.WithOrigins("https://localhost:44340"
    
                                                )
                            .AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
                        });
                });
                services.AddControllers().AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                    options.SerializerSettings.MaxDepth = 100;
    
                    options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                });
                services.Configure<GzipCompressionProviderOptions>(options =>
                {
                    options.Level = CompressionLevel.Fastest;
                });
                services.AddDbContext<BooksServerContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("BooksServerContext"))
    
               );
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseCors(options => options.WithOrigins("https://localhost:44340"));
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                    // 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.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseRouting();
                app.UseResponseCaching();
                app.UseCors(MyPolicy);
                app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
            }
        }

    data fetching properly but i cannot insert I checked in postman its working. i post in json format, but its not working here in project

    Friday, July 10, 2020 11:41 AM

Answers

  • User475983607 posted

    Did you take a look at the response in dev tools?  You can find the response in the Network view.  Click on the request that caused the CORS error then click the response tab.  From there just read the response.  Sometimes there an error message and the error message is missing the CORS headers.

    Other than that, there no way for the community to verify your CORS configuration is correct.   This is an example of mine which functions are expected.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        { 
            options.AddDefaultPolicy(
            builder =>
            {
                builder.WithOrigins("https://localhost:44331")
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
            });
        });
    
    
        services.AddControllers()
            .AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
    
    }
    
    // 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();
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 10, 2020 3:44 PM

All replies

  • User475983607 posted

    data fetching properly but i cannot insert I checked in postman its working. i post in json format, but its not working here in project

    CORS is browser security allowing/denying cross site scripting.  PostMan does not fall under this category so CORS is irrelevant.  Since PostMan works that means there is a problem with your code.  

    Remove the GZip compression and try again.  If you are still unable to make a POST (or PUT) then open the browser dev tools to review the HTTP response.  Perhaps there is an error.

    Friday, July 10, 2020 12:01 PM
  • User2041008840 posted

    I tried by removing Gzip but its still showing this error on post method.

    Access to fetch at 'https://localhost:44341/api/Customers' from origin 'https://localhost:44340' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. 


    Friday, July 10, 2020 3:26 PM
  • User475983607 posted

    Did you take a look at the response in dev tools?  You can find the response in the Network view.  Click on the request that caused the CORS error then click the response tab.  From there just read the response.  Sometimes there an error message and the error message is missing the CORS headers.

    Other than that, there no way for the community to verify your CORS configuration is correct.   This is an example of mine which functions are expected.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        { 
            options.AddDefaultPolicy(
            builder =>
            {
                builder.WithOrigins("https://localhost:44331")
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
            });
        });
    
    
        services.AddControllers()
            .AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
    
    }
    
    // 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();
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 10, 2020 3:44 PM
  • User2041008840 posted

    Yes. Checked it response tab it showing 400 status. So I double clicked on and see Name field is required. But when I add this in startup. its start accepting Post Put 

    .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();

    Thank you so much sir. You always help me. and gives proper solution. 

    Friday, July 10, 2020 5:44 PM