Resolving Cross-Origin Resource Sharing (CORS) Issues in Web API
When developing web applications, you may encounter the following CORS error:
Access to XMLHttpRequest at 'http://xxx.xxx' from origin 'http://localhost:8002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Rediretc is not allowed for a preflight request.
This typically occurs when your frontend application attempts to make requests to a different domain or port than the one it was served from.
Approach 1: Manual Header Configuration
You can manually add required CORS headers in your application code:
// In your controller or global.asax
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
Alternatively, configure headers through web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0"
path="*."
verb="*"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Approach 2: Using Microsoft.AspNet.WebApi.Cors Package
A more structured approach involves enabling CORS via configuration settings.
Add origins list to web.config:
<appSettings>
<!-- CORS Origins -->
<add key="AllowedCorsOrigins" value="http://localhost:8002,http://localhost:9536" />
</appSettings>
In WebApiConfig.cs, register the CORS functionality:
public static class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
var corsOrigins = ConfigurationManager.AppSettings["AllowedCorsOrigins"];
var corsPolicy = new EnableCorsAttribute(corsOrigins, "*", "*")
{
SupportsCredentials = true
};
configuration.EnableCors(corsPolicy);
configuration.MapHttpAttributeRoutes();
configuration.Routes.MapHttpRoute(
name: "DefaultRoute",
routeTemplate: "api/{controller}/{identifier}",
defaults: new { identifier = RouteParameter.Optional }
);
}
}
To use this method, install the Microsoft.AspNet.WebApi.Cors NuGet package first.