0

When I do axios post by React JS, I get the following CORS error to ASP.Net Core side.

Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. https://localhost:5001/api/vendorregistration

I installed the following as my Nuget Packages and did not apply any other form below but it didn't work.

  • Microsoft.AspNet.Cors. 5.2.7 Version
  • Microsoft.AspNetCore.Cors 2.1.1 Version

How to enable Cors for every type of request in asp.net core 3.1

Startup.cs

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.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddCors(o => o.AddPolicy("ReactPolicy", builder =>
        {
            builder.AllowAnyHeader()
                   .AllowAnyMethod()
                   .AllowAnyOrigin();
               //    .AllowCredentials();
        }));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseHttpsRedirection();

        app.UseCors("ReactPolicy");
        app.UseMvc();

    }
}

VendorRegistrationController.cs

namespace Bait.Controllers
{

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("ReactPolicy")]

ReactJS Side RegistrationForm.tsx

 const handleFormSubmit = async (values: any): Promise<any> => {
   const response = await axios.post<User>('https://localhost:5001/api/vendorregistration', { data: values })
   console.log(response);
 };
3
  • Your configuration for cors policy is correct and I also copied your code to my newly created asp.net core2.1 project and it really worked, so I'm afraid you need to rebuild or just reopen your visual studio and then restart your application and try again, it's more likely not take effect in my opinion. Commented Sep 22, 2021 at 2:26
  • @TinyWang I uninstalled the project and re-installed it and added the same files. However, when I trigger the project on the ReactJS side, I still get the same error. I wonder if it's HomeController.cs or something else I forgot? Commented Sep 30, 2021 at 14:07
  • 1
    Many thanks sir and happy coding : ) Commented Oct 1, 2021 at 8:35

2 Answers 2

1

Could you pls check my code snippet as it worked for me. I copied your startup file so I just put the using packages here.

My test controller:

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace WebAppMVCcore2.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("ReactPolicy")]
    public class HelloController : Controller
    {
    
        [HttpPost]
        public string Index()
        {
            return "hello";
        }
    }
}

And my startup file:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebAppMVC_core2
{}

And my test react code:

import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {

  constructor(props){
    super(props);
  }

  componentDidMount(){
      const response = axios.post('https://localhost:44326/api/hello').then(res=>{
        console.log('res=>',res);            
      })
      console.log(response);
  }
  
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

I updated my controller file. This worked for me. Thanks
@Yavuz I'm glad to hear you solved your issue, you updated your controller method sir? That sounds amazing. Anyway it's great. Thanks for your reply sir and could you pls accept my post as the answer? I really appreciate you for it.
0

you do not have to use in every actions in the controller. just put app.UseCors("ReactPolicy"); line before app.UseStaticFiles(); line

app.UseCors("ReactPolicy");

Hope it'll work!

1 Comment

app.UseStaticFiles(); first app.UseCors("ReactPolicy"); I added. However, it didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.