0
I have a project where the back is in . net and the front in React.
I can do all CRUD operations with Postman, however in React I get Cors error.
I understand the cause of the problem, but I cannot find the solution. I consulted several sites (list at the end) following the guidelines, but without success.
To make sure there is no problem with the front, I went up an api with php, "solved Cors" and everything worked fine. I tried using proxy in React and browser extensions where they "solve Cors", but problem persists with . net.
Could anyone help? I removed all code that didn’t work in my tests.
setup js.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using FAP.Models;
namespace FAP
{
    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.AddDbContext<FapContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
            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.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
Controller
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using FAP.Models;
namespace FAP.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SolucaoPadroesController : ControllerBase
    {
        private readonly FapContext _context;
        public SolucaoPadroesController(FapContext context)
        {
            _context = context;
        }
        // GET: api/SolucaoPadroes
        [HttpGet]
        public async Task<ActionResult<IEnumerable<SolucaoPadrao>>> GetSolucaoPadrao()
        {
            return await _context.SolucaoPadrao.ToListAsync();
        }
        // GET: api/SolucaoPadroes/5
        [HttpGet("{id}")]
        public async Task<ActionResult<SolucaoPadrao>> GetSolucaoPadrao(int id)
        {
            var solucaoPadrao = await _context.SolucaoPadrao.FindAsync(id);
            if (solucaoPadrao == null)
            {
                return NotFound();
            }
            return solucaoPadrao;
        }
        // PUT: api/SolucaoPadroes/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutSolucaoPadrao(int id, SolucaoPadrao solucaoPadrao)
        {
            if (id != solucaoPadrao.Id)
            {
                return BadRequest();
            }
            _context.Entry(solucaoPadrao).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SolucaoPadraoExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return NoContent();
        }
        // POST: api/SolucaoPadroes
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPost]
        public async Task<ActionResult<SolucaoPadrao>> PostSolucaoPadrao(SolucaoPadrao solucaoPadrao)
        {
            _context.SolucaoPadrao.Add(solucaoPadrao);
            await _context.SaveChangesAsync();
            return CreatedAtAction("GetSolucaoPadrao", new { id = solucaoPadrao.Id }, solucaoPadrao);
        }
        // DELETE: api/SolucaoPadroes/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<SolucaoPadrao>> DeleteSolucaoPadrao(int id)
        {
            var solucaoPadrao = await _context.SolucaoPadrao.FindAsync(id);
            if (solucaoPadrao == null)
            {
                return NotFound();
            }
            _context.SolucaoPadrao.Remove(solucaoPadrao);
            await _context.SaveChangesAsync();
            return solucaoPadrao;
        }
        private bool SolucaoPadraoExists(int id)
        {
            return _context.SolucaoPadrao.Any(e => e.Id == id);
        }
    }
}
- Consuming a WEB API in Visual Studio
- https://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Controle_Acesso_CORS
- https://www.hexacta.com/2014/09/15/How-to-enable-CORS-on-your-Web-API
- https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#Cors-with-named-policy-and-middleware
- https://www.html5rocks.com/en/tutorials/cors/
Supposedly just set up as at this link. Try again and make sure that the address is exactly the same as the front, including with http or HTTPS.
– tvdias