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
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
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.
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.
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();
});
}
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
Member
75 Points
161 Posts
Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight res...
Jul 10, 2020 11:41 AM|Prathamesh Shende|LINK
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
CustomersService.cs
Customer.cs
Startup.cs in web api
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
All-Star
53041 Points
23612 Posts
Re: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight...
Jul 10, 2020 12:01 PM|mgebhard|LINK
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.
Member
75 Points
161 Posts
Re: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight...
Jul 10, 2020 03:26 PM|Prathamesh Shende|LINK
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.
All-Star
53041 Points
23612 Posts
Re: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight...
Jul 10, 2020 03:44 PM|mgebhard|LINK
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.
Member
75 Points
161 Posts
Re: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight...
Jul 10, 2020 05:44 PM|Prathamesh Shende|LINK
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.