I am using ASP.NET CORE and I enabled CORS using this documentation, but I am having issues with preflight request coming from chrome browser that are making OPTION request that failing prior POST request is initiated.

I am using angularJS to make a POST request to cross domain URL.

Below is my configuration in startup.cs file that is configured to enable CORS globally.

public void ConfigureServices(IServiceCollection services)
    {
            // MVC
            services.AddMvc()
            .AddJsonOptions(
                    opt =>
                    {
                        opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Api convert all property names to CamelCase.
                        opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                    }
            );

            // Add service and create Policy with options
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });

            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("CorsPolicy"));
            });
}

AngularJS script:

var config = {
        url: get_servers_url,
        method: 'POST',
        data: data,
        'withCredentials': true,
        headers: {
            'Accept': 'application/json, text/javascript',
            'Content-Type': 'application/json; charset=utf-8'
        }
    }

    var servers = $http(config).then(function (response) {
        console.log(response.data);
        if (response.data.search.length > 0) {
            $scope.searchMessage = null;
            $scope.servers = response.data;
        }
        else {
            $scope.searchMessage = "No results found!";
            $scope.servers = null;
        }
    });

Since I am using AllowAnyHeader & AllowAnyMethod in ASP, it should allow any header and method, but not sure why it is failing. I am able to use CORS with all the GET request, but only failing with POST request.

I also tried below code in AngularJS, but it is not helping.

App.config(['$httpProvider', function($httpProvider) {
    delete $httpProvider.defaults.headers.common["X-Requested-With"]
}]);

Related posts

Recent Viewed