Sponsored

Wednesday, November 4, 2026

How to Configure CORS for a React and ASP.NET Core Application


By Kashmitha Madushan · Prepared 4 November 2026.

When a React app calls an ASP.NET Core API on a different origin, the browser may block the request unless the API returns the correct cross-origin headers. A CORS failure is generally fixed on the server, not by disabling browser security.

Example development setup

Assume React is running at http://localhost:5173 and your API uses a different origin. Replace the addresses in this guide with your actual local addresses.

Configure an explicit origin in Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
    options.AddPolicy("ReactDev", policy =>
        policy.WithOrigins("http://localhost:5173")
              .AllowAnyHeader()
              .AllowAnyMethod());
});

var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("ReactDev");
app.UseAuthorization();
app.MapControllers();
app.Run();

Keep CORS middleware in the correct position in your request pipeline. Your actual application might also use authentication, custom middleware, or endpoint-specific policies.

Common mistakes

  • Using the wrong frontend port or scheme.
  • Adding CORS settings only in React.
  • Using wildcard origins with credentials; this combination is not allowed.
  • Confusing a backend 401/403/500 response with a CORS configuration problem.

Debugging checklist

Open browser developer tools, select Network, inspect the OPTIONS preflight where present, and check the API response and console error. Test a known-good endpoint before expanding the policy.

Official reference: ASP.NET Core CORS documentation. Verify the sample against your target .NET version before publishing.

Written by Kashmitha Madushan, Associate DevOps Engineer and full-stack developer. Software versions and tools can change; check the linked official documentation before applying steps to a production system.

No comments:

Post a Comment

Practical developer tutorials, AI tool comparisons, troubleshooting guides and free software resources.

Search This Blog

Powered by Blogger.

Blog Archive

Git troubleshooting: choose the right fix without losing work

Choose a Git command from the change you want to inspect, not from a list of commands to try. Staged edits, unstaged edits, untracked files ...