Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Resolving Cross-Origin Resource Sharing (CORS) Issues in Web API

Tech Aug 13 15

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.