1

在旧的 chrome 版本中,我可以使用 jquery ajax 向 wcf rest 服务发布请求,尽管它们不是同一个域,我向服务器添加了 CORS 支持,在我更新到 30.0.1599.101 版本后,它不再工作了。我用 rest 客户端、safari、IE 和 firefox 测试,它们可以工作。此外,仍然支持获取请求。代码片段如下,

function getTempValue(pointname, succeed) {

        var data = '{"pointname":"' + pointname + '"}';
        var invoker = new InterfaceInvoker("http://localhost/UCBService/UCBDemoService.svc", "GetPointValue", data, "POST");
        invoker.Invoke(succeed);
    }
function InterfaceInvoker(newUrl, newInterfaceName, newParameter, newRequestType) {
    var url, interfaceName, parameter, requestType;
    this.GetUrl = function () {
    return url;
};
this.SetUrl = function (newUrl) {
    url = newUrl || "no url setted";
};
this.GetInterfaceName = function () {
    return interfaceName;
};
this.SetInterfaceName = function (newInterfaceName) {
    interfaceName = newInterfaceName || "no interface setted";
};
this.GetParameter = function () {
    return parameter;
};
this.SetParameter = function (newParameter) {
    parameter = newParameter;
};
this.GetRequestType = function () {
    return requestType;
};
this.SetRequestType = function (newRequestType) {
    requestType = newRequestType || "no requestType setted";
};
this.SetUrl(newUrl);
this.SetInterfaceName(newInterfaceName);
this.SetParameter(newParameter);
this.SetRequestType(newRequestType);
}
InterfaceInvoker.prototype.Invoke = function (successCallBack, failureCallback) {
    var Type = this.GetRequestType(),
        Url = this.GetUrl() + "/" + this.GetInterfaceName(),
        Data = this.GetParameter(),       
        ContentType = "application/json; charset=utf-8",
        DataType = "json",
        ProcessData = true;
    $.support.cors = true;
 return $.ajax({
 type: Type,
 async: "true",      
        url: Url,                       // Location of the service
        data: Data,                     //Data sent to server
        contentType: ContentType,       // content type sent to server
        dataType: DataType,             //Expected data format from server
        processdata: ProcessData,       //True or False
        timeout: 3000000,                //Timeout setting 
        success: successCallBack || function () { alert("Succeded!") }, //On Successfull service call
        error: failureCallback || function (jqXHR, textStatus, errorThrown) { 
        alert("Failed!" + jqXHR.statusText); }      // When Service call fails
    });
};

回复信息如下,

Request URL:http://localhost/UCBService/UCBDemoService.svc/GetPointValue)
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost
Origin:http://localhost:51818
Referer:
    http://localhost:51818/HTMLPage1.htm
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko)       Chrome/30.0.1599.101 Safari/537.36


Response Headers
Access-Control-Allow-Headers:Accept, content-type
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin:*
Allow:POST
Cache-Control:private
Content-Length:1565
Content-Type:text/html; charset=UTF-8
Date:Wed, 23 Oct 2013 08:01:23 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

谢谢,

4

2 回答 2

0

I encountered this same error recently while helping a friend. The problem is that Chrome incorrectly ignored failed pre-flight requests. This bug originated in webkit. However, the problem that you are having has to do with IIS 7 with .net 4.0 sending a 405 on the pre-flight OPTIONS call. The fix for this problem is to write your own OPTIONS request handler. This blog entry does a great job explaining it. http://evolpin.wordpress.com/2012/10/12/the-cors/

Taken directly from the post:

First you need to create a class that will intercept OPTIONS and allow them to always succede public class CORSModule : IHttpModule { public void Dispose() { }

    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += delegate
        {
            if (context.Request.HttpMethod == "OPTIONS")
            {
                var response = context.Response;
                response.StatusCode = (int)HttpStatusCode.OK;
            }
        };
    }
}

Then you need to modify your web.config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type,Authorization" />
    </customHeaders>
  </httpProtocol>
  <modules>
    <add name="CORSModule" type="CORSModule" />
  </modules>
</system.webServer>

This will intercept the OPTIONS request and return 200. Note that it is not secure and that you should add appropriate security. And as a final note, upgrading to .net 4.5 is considered the best fix.

于 2013-11-05T20:55:51.653 回答
0

也不太确定解决方案(在为我的问题寻找解决方案时偶然发现了您的问题:D),但我找到了链接(http://praneeth4victory.wordpress.com/2011/09/29/405-method- not-allowed/)这让我认为 OPTIONS-Preflight-Request 在新的 Chrome 版本中不再是可选的,而是强制性的。我会尝试实现对 OPTIONS-Request 的回答,看看是否有帮助。

编辑:是的,事实证明这是问题所在。我添加了

if request.method == "OPTIONS":
    response = Response()
    response.headers.add("Access-Control-Allow-Methods", "GET,POST,PUT,DEL")
    response.headers.add('Access-Control-Allow-Origin', "*")
    response.headers.add('Access-Control-Allow-Credentials', 'true')
    response.headers.add('Access-Control-Allow-Headers', 'Authorization')
    return response

对于我的请求处理方法(仅用于测试,这肯定可以做得更好:D)并且 jQuery 不再抱怨。

于 2013-11-01T10:27:35.407 回答