Cors Error - Visual Studio . Net Web API React

Asked

Viewed 147 times

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);
        }
    }
}
  • 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.

1 answer

0


Understanding CORS

This happened because CORS is a browser security implementation. It is the browser that blocks the request.

The server, in this case, has only the role of notifying, when asked, whether an origin is allowed or not.

This means that no matter how much it says it does not recognize the source, a server-to-server request is not blocked. Including the request that makes the CORS query is an additional request that uses the OPTIONS method (monitor this with devtools).

Solution

This is a startup.Cs that enables CORS.

Points of attention:

  • services Addcors
  • Builder.Withorigins
  • app.usecors
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("http://example.com",
                                        "http://www.contoso.com");
                });
            });

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

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseCors(MyAllowSpecificOrigins); 

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }

Link to the Documentation https://docs.microsoft.com/pt-br/aspnet/core/security/cors?view=aspnetcore-3.1

  • I had already tried, but without success.

  • I did, but I handled a lot of things. Now I’m going to remove the excess and see what really worked. I find, I report here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.