How to resolve CORS issue in C# ASP.NET WebAPI?

Cross-Origin Resource Sharing (CORS) is a security mechanism that uses additional HTTP headers to allow web applications running at one origin to access selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

For example, consider an application with its front-end served from https://demodomain-ui.com and backend from https://demodomain-service.com/api. When the UI tries to make API calls to the backend, browsers restrict these cross-origin HTTP requests for security reasons, resulting in CORS errors.

CORS Request Flow Frontend demodomain-ui.com Port: 3000 Backend API demodomain-service.com Port: 5000 HTTP Request CORS Error (Blocked) Different Origins: Domain, Protocol, or Port

CORS Headers

The CORS standard uses specific HTTP headers to control cross-origin access −

  • Access-Control-Allow-Origin − Specifies which origins can access the resource

  • Access-Control-Allow-Methods − Lists allowed HTTP methods (GET, POST, PUT, DELETE)

  • Access-Control-Allow-Headers − Specifies allowed request headers

  • Access-Control-Allow-Credentials − Indicates if cookies can be sent

  • Access-Control-Max-Age − How long preflight responses can be cached

Enabling CORS Globally in ASP.NET Web API

For ASP.NET Web API (.NET Framework), first install the Microsoft.AspNet.WebApi.Cors NuGet package. Then configure CORS in the WebApiConfig.Register method −

using System.Web.Http;
using System.Web.Http.Cors;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable CORS globally
        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        // Web API routes
        config.MapHttpAttributeRoutes();
        
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Enabling CORS at Controller Level

You can enable CORS for specific controllers using the [EnableCors] attribute −

using System.Web.Http;
using System.Web.Http.Cors;

namespace DemoWebApplication.Controllers
{
    [EnableCors(origins: "https://demodomain-ui.com", headers: "*", methods: "*")]
    public class DemoController : ApiController
    {
        public IHttpActionResult Get()
        {
            var data = new { Message = "Hello from API", Status = "Success" };
            return Ok(data);
        }

        public IHttpActionResult Post([FromBody]string value)
        {
            return Ok(new { Result = "Data received", Value = value });
        }
    }
}

Enabling CORS at Action Level

For more granular control, apply CORS to specific action methods −

using System.Web.Http;
using System.Web.Http.Cors;

namespace DemoWebApplication.Controllers
{
    public class ProductController : ApiController
    {
        [EnableCors(origins: "https://demodomain-ui.com", headers: "*", methods: "GET")]
        public IHttpActionResult GetProducts()
        {
            var products = new[]
            {
                new { Id = 1, Name = "Laptop", Price = 999.99 },
                new { Id = 2, Name = "Mouse", Price = 25.50 }
            };
            return Ok(products);
        }

        [DisableCors]
        public IHttpActionResult DeleteProduct(int id)
        {
            return Ok(new { Message = "CORS disabled for this action" });
        }
    }
}

CORS in ASP.NET Core

For ASP.NET Core applications, configure CORS in Program.cs or Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin", policy =>
    {
        policy.WithOrigins("https://demodomain-ui.com")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});

var app = builder.Build();

// Configure pipeline
app.UseCors("AllowSpecificOrigin");
app.MapControllers();

app.Run();

CORS Configuration Options

Parameter Description Example
Origins Allowed origins (domains) "https://example.com" or "*" for all
Headers Allowed request headers "Content-Type,Authorization" or "*"
Methods Allowed HTTP methods "GET,POST,PUT" or "*"
Credentials Allow cookies/credentials true or false

Best Practices

  • Avoid using "*" for origins in production − specify exact domains for security

  • Use HTTPS for both frontend and backend in production environments

  • Apply CORS at controller level rather than globally when possible for better security

  • Test CORS policies using browser developer tools to verify proper headers

Conclusion

CORS configuration in ASP.NET Web API can be implemented globally, at controller level, or at action level using the [EnableCors] attribute. For production applications, specify exact origins instead of using wildcards and consider using HTTPS for secure cross-origin communication.

Updated on: 2026-03-17T07:04:36+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements