CORS and Deployment
Level: Intermediate
ℹ️ What You'll Learn
- CORS problem: Browser blocks frontend (localhost:3000) from calling API (localhost:5000) different origin
- CORS solution: API tells browser "I allow requests from localhost:3000", browser allows request
- Same-origin policy: Browser security (prevents malicious websites from stealing data)
AddCors(): Register CORS policy in Program.cs- Specific origins:
WithOrigins("http://localhost:3000", "https://react.example.com")allow specific frontend URLs AllowAnyOrigin(): Allow requests from any origin (DANGEROUS in production!)AllowAnyMethod(): Allow GET, POST, PUT, DELETE, PATCH (all HTTP methods)AllowAnyHeader(): Allow any request headers (Content-Type, Authorization, etc.)- Preflight request: Browser sends OPTIONS request first (asks "can I make this request?")
AllowCredentials(): Allow cookies/JWT tokens in requests (needed for authentication)- Development environment: CORS loose (
AllowAnyOrigin), React dev server calls API - Production environment: CORS strict (specific trusted origins only, not
AllowAnyOrigin) - appsettings.Production.json: Contains production-specific settings (different database, API URLs)
- Connection string management: Secure sensitive data (passwords, API keys) outside code (environment variables)
- Deployment targets: Azure App Service, Docker container, IIS Windows Server, Linux server
- SMS API checklist: CORS configured, HTTPS enabled, secrets not in code, environment-specific configs
CORS Problem
Frontend (React) at http://localhost:3000 cannot access API at http://localhost:5000 without CORS.
Enable CORS (Program.cs)
// Allow specific origin
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReact", builder =>
{
builder.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
app.UseCors("AllowReact");
Multiple origins:
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
Production:
builder.WithOrigins(
"https://app.sms.school",
"https://admin.sms.school")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
Environment Configuration
Development (appsettings.Development.json):
{
"Logging": {
"LogLevel": {
"Default": "Debug"
}
},
"AllowedOrigins": ["http://localhost:3000"]
}
Production (appsettings.Production.json):
{
"Logging": {
"LogLevel": {
"Default": "Error"
}
},
"AllowedOrigins": ["https://app.sms.school"],
"ConnectionStrings": {
"DefaultConnection": "Server=prod-db.azure.com;Database=SMS;..."
}
}
Deployment Options
Docker
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "SMS.Api.dll"]
docker build -t sms-api .
docker run -p 5000:80 sms-api
IIS
- Publish to folder:
dotnet publish -c Release - Deploy to IIS
- Configure application pool (.NET CLR)
- Enable HTTPS
Azure App Service
az webapp create -g mygroup -p myplan -n sms-api --runtime "DOTNET|8.0"
dotnet publish -c Release
az webapp deployment source config-zip -r "publish.zip"
Production Checklist
Database:
- ✓ Connection string secure
- ✓ Database backup strategy
- ✓ Indexes on frequently queried columns
API:
- ✓ HTTPS enabled
- ✓ Authentication working
- ✓ Error handling complete
- ✓ Logging configured
- ✓ CORS restricted
Security:
- ✓ No secrets in code
- ✓ API rate limiting
- ✓ Input validation
- ✓ SQL injection prevention
Testing:
- ✓ All tests passing
- ✓ Integration tests
- ✓ Load testing
Monitoring:
- ✓ Error logging
- ✓ Performance monitoring
- ✓ Health checks
Health Check Endpoint
[HttpGet("health")]
[AllowAnonymous]
public IActionResult Health()
{
return Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
}
Key Takeaways
- CORS = allow cross-origin
- Environment = dev/prod config
- Docker = containerized deployment
- HTTPS = always in production
- Monitoring = production insights
💡 Deployment Tip
Always use HTTPS in production. Never expose secrets.
⚠️ Deployment Issues
- Wrong connection string — Points to dev database
- CORS too open — AllowAnyOrigin in production
- No HTTPS — Credentials vulnerable
- No error logging — Can't debug issues
🤖Use AI to Learn Faster
Use ChatGPT, Claude, or Copilot to go deeper on CORS and Deployment. Try these prompts:
"How do I enable CORS for React frontend?""What's the difference between development and production config?""Should I use Docker or IIS for deployment?""Quiz me on deployment"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.
nexcoding.in
Have questions on your tech stack, ongoing projects, or need one-to-one training?