Nands
Nands

Reputation: 399

CORS in .NET Core 3.0

I have Web API developed in .NET Core 3.0 and am POSTing through React.js.

In Controller:

 [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        [HttpPost, Route("login")]
        [EnableCors()]
        public async Task<IActionResult> Login([FromBody]User user)
        {
            //code implementation
            return Ok(new { Status = "OK" });
        }
    }

In Startup:

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.AddCors();
            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.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

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

In React.js

const data = {
              UserName: "jack",
              Password: "def@123"
            };

            axios
              .post("https://localhost:44369/api/auth/login", {
                body: JSON.stringify(data),
                headers: {
                  "Content-Type": "application/json"
                }
              })

But I get below error:

OPTIONS https://localhost:44369/api/auth/login 415

Access to XMLHttpRequest at 'https://localhost:44369/api/auth/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

PS: please know that I have tried various other approaches but keep getting some or the other CORS error.

Upvotes: 0

Views: 503

Answers (1)

Nands
Nands

Reputation: 399

I was able to make it working as below:

In Controller:

[Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        [HttpPost, Route("login")]
        [EnableCors()]        
        public async Task<IActionResult> Login(User user)
        {
            //code implementation
            return Ok(new { Status = "OK" });
        }
    }

In Startup:

 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.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                    {
                        builder.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod();
                    });
            });
            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.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

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

In React.js :

const data = {
              UserName: "jack",
              Password: "def@123"
            };


axios.post("https://localhost:44392/api/auth/login", data);

Upvotes: 1

Related Questions