【发布时间】:2015-05-07 00:53:22
【问题描述】:
我有一个托管在 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 的属性并将这个类连接到我的服务并处理了 BeforeSendReply 方法以将访问控制方法添加为:
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 中创建测试调用时,这对我没有帮助。所以我把它从这里取出并添加到 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 错误并且我的标题不存在。 所以我继续并将这些标头放在 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
我还尝试在 WebInvoke 中更改为 Method="*"。但仍然无法正常工作。
提前致谢..
【问题讨论】:
标签: wcf iis cross-domain cors