Pop
Pop

Reputation: 525

CORS is enable in Web API but access is denied

I am prety sure CORS is enable in my Web API project but access is denied. Perhaps I misconfigure it?

Error:

Access to XMLHttpRequest at 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/PagingCriticalPart' from origin 'http://localhost:55817' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Ajax call:

<script type="text/javascript">
    $(document).ready(function () {
        var _tableId = 'tableCriticalParts';
        var _table = $('#' + _tableId).DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                url: 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/PagingCriticalPart',
                type: 'POST',
                contentType: "application/json",
                data: function (data) {
                    //debugger;
                    var model = {
                        draw: data.draw,
                        start: data.start,
                        length: data.length,
                        columns: data.columns,
                        search: data.search,
                        order: data.order
                    };
                    return JSON.stringify(model);
                },
                failure: function (result) {
                    debugger;
                    alert("Error occurred while trying to get data from server: " + result.sEcho);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    debugger;
                    alert("Error occurred while trying to get data from server!");
                }
                ,
                dataSrc: function (json) {
                    debugger;
                    for (key in json.Data) { json[key] = json.Data[key]; }
                    delete json['Data'];
                    return json.data;
                }
            }
            ,
            "columns": [
                { "data": "partNumber", title: "partNumber" },
                { "data": "partDescription", title: "partDescription" }
            ]
        });
    });
</script>

Web.config of Web API project:

<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>
</system.webServer>

WebApiConfig in Web API project:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        //set API to return JSON
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
}

Upvotes: 4

Views: 12195

Answers (1)

Kyle Polansky
Kyle Polansky

Reputation: 446

Since the line config.EnableCors() enables CORS without any explicit configuration, my guess is that your custom headers are being overridden by the CORS module.

You can try adding a global CORS configuration when enabling it, such as:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);

        // Rest of config ...
    }
}

I would recommend using this approach (with a more restrictive set of origins) and deleting the <customHeaders> from your web.config.

Source: https://enable-cors.org/server_aspnet.html (Enabling Globally)

Upvotes: 3

Related Questions