<!-- web.config in the virtual directory serving Angular files (e.g., /angular-app/web.config) -->
<configuration>
<system.webServer>
<!-- Enable CORS for the virtual directory -->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.End();
}
}
using System;
using System.Web;
public class CorsHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += OnBeginRequest;
}
public void Dispose()
{
}
private void OnBeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
// Get the origin from the request
string origin = context.Request.Headers["Origin"];
// Check if the origin is allowed (replace "alloweddomain1.com" and "alloweddomain2.com" with your actual allowed domains)
if (!string.IsNullOrEmpty(origin) && (origin.Contains("alloweddomain1.com") || origin.Contains("alloweddomain2.com")))
{
// Allow the specific origin
context.Response.AddHeader("Access-Control-Allow-Origin", origin);
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
}
if (context.Request.HttpMethod == "OPTIONS")
{
context.Response.End();
}
}
}
<configuration>
<system.webServer>
<modules>
<add name="CorsHttpModule" type="YourNamespace.CorsHttpModule, YourAssemblyName" />
</modules>
</system.webServer>
</configuration>
Related