2

我在我的 Web API 方法中启用了 CORS

    [EnableCors]
    public HttpResponseMessage PostDeviceControl(DeviceAccessRequest deviceAccessRequest)
    {
        var deviceId = deviceAccessRequest.DeviceId;
        var returnStatus = HttpStatusCode.OK;


        var deviceAccessResponse = new DeviceAccessResponse(deviceAccessRequest.RequestId)
            {
                Message = ""
            };
        var response = Request.CreateResponse<DeviceAccessResponse>(returnStatus, deviceAccessResponse);
        return response;
    }

使用 jQuery 调用 web 方法

    var url = "http://localhost:55208/api/accesspanel";

    var request = {
        RequestId: "123",
        DeviceId: "ACU-B2-01-R1",
        AccessType: "Unlock",
        LoginId: "tester",
        Password: "tester"
    };

    $.post(
        url,
        request,
        function (x, y, z) {
            alert(x + ' ' + y + ' ' + z);
        },
        "json"
    );

以上工作正常。

但是,当我尝试使用纯 javascript 时:

        try {
            var xmlreq = null;
            if (window.XMLHttpRequest)
                xmlreq = new XMLHttpRequest();
            else if (window.ActiveXObject)
                xmlreq = new ActiveXObject("Microsoft.XMLHTTP");

            var data2 = {
                RequestId: "123",
                DeviceId: "ACU-B2-01-R1",
                AccessType: "Unlock",
                LoginId: "tester",
                Password: "tester"
            };

            xmlreq.open("POST", "http://localhost:55208/api/accesspanel", false);
            xmlreq.setRequestHeader("Accept", "application/json");
            xmlreq.setRequestHeader("Content-type", "application/json; charset=utf-8");


            xmlreq.onreadystatechange = function() {
                if (xmlreq.readyState == 4 && xmlreq.status == 200) {
                    if (typeof(xmlreq.responseText) == "unknown") {
                        alert("No Data");
                    } else {
                        alert('ok');
                        var objResult = xmlreq.responseText;
                        //document.getElementById('lblGrantAccessResult').innerHTML = objResult;  
                    }

                }
            };
            alert('1');
            xmlreq.send(data2);
        }
        catch (e) {
            alert(e);
        }

这是我在 Chrome 的调试控制台中遇到的错误

OPTIONS http://localhost:55208/api/accesspanel 405 (Method Not Allowed) localhost:132
(anonymous function) localhost:132
XMLHttpRequest cannot load http://localhost:55208/api/accesspanel. Origin http://localhost:54873 is not allowed by Access-Control-Allow-Origin. localhost:132

我正在使用此处描述的方法启用 CORS:http: //blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api-rc-version .aspx

4

0 回答 0