【问题标题】:CORS is enable in Web API but access is denied在 Web API 中启用了 CORS,但访问被拒绝
【发布时间】:2019-04-18 02:40:56
【问题描述】:

我很确定我的 Web API 项目中启用了 CORS,但访问被拒绝。也许我配置错误?

错误:

从源“http://localhost:55817”访问位于“http://localhost/ControlTower2WebAPI/api/PurchaseOrder/PagingCriticalPart”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

Ajax 调用:

<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 API 项目的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>
</system.webServer>

Web API 项目中的WebApiConfig:

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"));
    }
}

【问题讨论】:

    标签: c# ajax asp.net-web-api cors


    【解决方案1】:

    由于config.EnableCors() 行无需任何显式配置即可启用 CORS,我猜测您的自定义标头已被 CORS 模块覆盖。

    启用时可以尝试添加全局CORS配置,如:

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

    我建议使用这种方法(具有更严格的来源集)并从您的 web.config 中删除 &lt;customHeaders&gt;

    来源:https://enable-cors.org/server_aspnet.html(全球启用)

    【讨论】:

    • 感谢您帮我解决了这个问题。我添加了“全部允许”策略,但在配置时我没有指定该策略。
    猜你喜欢
    • 2018-07-19
    • 2016-08-13
    • 1970-01-01
    • 2015-01-23
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多