WCF中的CORS:web.config条目没有帮助,但(等效?)Global.asax方法有效!为什么呢?

时间:2015-06-02 17:47:20

标签: c# jquery wcf google-chrome cors

我有一个由JQuery(通过chrome)使用的WCF Restful Service。我用POST方法检测到Cross-Origin问题,并试图解决它。当我向项目中添加Global.asax并拦截 OPTION 请求并对其作出积极响应时,事情完美无缺,如下面的代码所示:

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

上面的代码正如预期的那样工作。但是,我认为会做同样的(在web.config中)下面的这个不起作用

<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    <add name="Access-Control-Max-Age" value="1728000" />
  </customHeaders>
</httpProtocol>
<!--
    To browse web app root directory during debugging, set the value below to true.
    Set to false before deployment to avoid disclosing web app folder information.
  -->
<directoryBrowse enabled="true"/>

如下所示,chrome中的错误详细信息:

  

无法加载资源:服务器响应状态为405   (不允许的方法)       Index.html:1 XMLHttpRequest无法加载http://localhost:61481/ServiceRest.svc/CreateUser。无效的HTTP状态   代码405       Index.html:1未捕获的SyntaxError:意外的标记o

我真的很好奇我做错了什么,并试图填补我对它的理解的空白!任何帮助将不胜感激。谢谢提前

其他信息: 服务定义如下:

[OperationContract]
        [WebInvoke(UriTemplate = "/CreateUser", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        int CreateUser(UserData user);

JQuery如下

$.ajax({
         type: "POST",
         url: serviceUrl,
         data: JSON.stringify( {
             "Password" : "String content",
             "UserID" : "String content",
             "UserName" : "String content",
             "UserRole" : "String content"
         }),
         contentType: "application/json",
         dataType: "json",
         success: OnSuccess,
         error: OnError
         });

0 个答案:

没有答案