WCF处理CORS&选项VERB

时间:2015-03-05 15:26:14

标签: wcf iis cross-domain cors

我在IIS上托管了一个wcf服务。 几乎所有的文件都说要启用cors,你应该处理OPTIONS VERB。 (飞行前请求)

我有一个签名为:

的方法
[OperationContract]
        [FaultContract(typeof(ExceptionManager))]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            UriTemplate = "PostLog")]
        string PostLog(List<LoginEntry> LoginLog);

我创建了一个源自IServiceBehavior&amp;把这个班级连接到我的服务和处理BeforeSendReply方法将Acces Control方法添加为:

public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{

    var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
    httpHeader.Headers.Add("Access-Control-Allow-Origin", "*");

    httpHeader.Headers.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
    httpHeader.Headers.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");

}

当我在firefox中创建一个testcall时,这对我没有帮助。所以我从这里拿出来&amp;在Global.asax文件中将其添加为

protected void Application_BeginRequest(object sender, EventArgs e)
        {
                           HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            HttpContext.Current.Response.Cache.SetNoStore();

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");

                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");

                HttpContext.Current.Response.End();

            }
        }

我可以在firefox 403中看到错误&amp;我的标题不存在。 所以我继续前进将这些标头放在IIS设置中(自定义标头选项卡)。 (我冒着在每个回复中发送这些回复的风险)。 现在我可以在firefox中看到响应中的那些标题,但我仍然得到403错误。 这是响应头:

HTTP/1.1 403 Forbidden
Connection: Keep-Alive
Content-Length: 1758
Date: Thu, 05 Mar 2015 14:47:25 GMT
Content-Type: text/html
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, Accept

我也尝试过改为方法=&#34; *&#34;在WebInvoke中。但仍无法让它发挥作用。

先谢谢..

1 个答案:

答案 0 :(得分:1)

所以终于搞定了。 这篇文章帮助了我。

enabling cross-origin resource sharing on IIS7

原来问题出在IIS 6站点设置中。

通过以下步骤解决:

在IIS中,选择网站 - &gt; RightClick(属性) - &gt;

在目录选项卡下选择配置按钮。

映射选项卡下。搜索扩展名(.svc) 单击“编辑”。搜索标签&#34;限制动词为&#34;。

以前的价值是&#34; GET,HEAD,POST,DEBUG&#34;

取代它&#34; GET,HEAD,POST,DEBUG,OPTIONS&#34;

另外,我从IIS中移除了所有这些头文件配置(因为我已经在管理它们Global.asax)。