1

I'm working on a web app using React for the frontend and ASP.NET Core for the backend.

This is code from my Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(builder =>
            {
                builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
            });
    });
}

This is my full API controller, which is working fine from Chrome when debugging with ISS in Visual Studio 2022.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace AsignacionesBackend.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ApiController : ControllerBase
    {
        private readonly ILogger<ApiController> _logger;

        public ApiController(ILogger<ApiController> logger)
        {
            _logger = logger;
        }

        [Route("Login")]
        public IActionResult Login()
        {
            JsonUser body = new JsonUser("hola", "buenas");
            body.Token = "tokendeprueba";
            JsonResult json = new JsonResult(body);
            return json;
        }

        public class JsonUser
        {
            public string User { get; set; }
            public string Pass { get; set; }
            public string Token { get; set; }

            public JsonUser(string user, string pass)
            {
                User = user;
                Pass = pass;
            }
        }
    }
}

This is the React code that is calling the API.

let result = fetch("https://localhost:5001/Api/Login");
result = await (await result).json;
console.log(result);

I'm receiving this error in the Chrome console when executing the React code:

Access to fetch at 'https://localhost:5001/Api/Login' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I'm new to both ASP.NET and React so any kind of help or tip is welcome. If you need more info I'll edit the question.

2
  • 2
    Did you add app.UseCors(); after app.UseRouting in Configure method in startup? Commented Apr 12, 2022 at 11:56
  • Nope, this was the issue, thank you so much. I saw several tutorials saying that I needed it and other saying that I needed the services.AddCore and I tried both, but didn't think I actually needed both at the same time. Commented Apr 12, 2022 at 12:04

2 Answers 2

2

CORS is ASP.NET is added in two steps:

  1. Add required services which is done in ConfigureServices in Startup
  2. Add CORS middleware which is done in Configure in Startup

From what you've shown I assume you've missed step 2. In your Configure method in Startup you should add call to UseCors() AFTER UseRouting().

Here is the official page about CORS. Note: examples there are using .NET 6 minimal api, but the idea stays the same - add services then add middleware.

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

1 Comment

The latest versions of IIS don't use the CORS configuration of .NET, you need to create or modify a file named web.config in your API root. Here is how to configure this.
0

Your Problem is, that your dev server on localhost:3000 is sending an cors header.

Take a look here: https://create-react-app.dev/docs/proxying-api-requests-in-development/

Comments

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.