0

Flutter web call to .net core api error 'Access-Control-Allow-Origin'

Help me i want flutter-Web call api

i use .net core api

how to allow 'Access-Control-Allow-Origin' on .net core api

code in Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace test_api
{
    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        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.AddControllers();
        }

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

            app.UseCors(MyAllowSpecificOrigins);

            // app.UseResponseCaching();

            app.UseAuthorization();

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

Flutter Web error

1 Answers1

0

The error means that your api (this unrelated to flutter) has blocked the request due to CORS policy. CORS blocks request from other IP. So you pretty much have to enable it.

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

Follow the guidelines and the answers here. Try to search for your specific asp.net core version. Furhtermore the EnableCors attribute on top of the controllers is required for this to work. Your allow only specific origins simply does not specify any kind of hosts. It specifies only the name of the policy and also you havent used in the services

A_kat
  • 1,459
  • 10
  • 17