我花了7个小时绞尽脑汁想弄清楚这个问题。我在整个网络上进行了搜索,但没有运气。我有一个 Angular 应用程序正在向 WCF 命令行托管服务应用程序发出请求。我设法通过使用这两个类来实现 CORS:
public class CustomHeaderMessageInspector : IDispatchMessageInspector
{
Dictionary<string, string> requiredHeaders;
public CustomHeaderMessageInspector(Dictionary<string, string> headers)
{
requiredHeaders = headers ?? new Dictionary<string, string>();
}
public object AfterReceiveRequest(ref Message request,
System.ServiceModel.IClientChannel channel,
System.ServiceModel.InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
foreach (var item in requiredHeaders)
{
httpHeader.Headers.Add(item.Key, item.Value);
}
}
}
And:
public class EnableCorsBehavior : BehaviorExtensionElement, IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{ }
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{ }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
var requiredHeaders = new Dictionary<string, string>();
requiredHeaders.Add("Access-Control-Allow-Origin", "*");
requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
}
public void Validate(ServiceEndpoint endpoint) { }
public override Type BehaviorType
{
get { return typeof(EnableCorsBehavior); }
}
protected override object CreateBehavior()
{
return new EnableCorsBehavior();
}
}
将此自定义扩展添加到 app.config 文件解决了我的 CORS 问题。我当前的问题是每当我发出 POST 请求时,都会收到错误:
Request Method:OPTIONS
Status Code:405 Method Not Allowed
我对 C# 很陌生,我似乎找不到在哪里放置可以让我克服这个问题的代码。我有一个想法,它应该放置在 BeforeSendReply() 方法中的某个位置。请帮我!我真的会非常非常感激!
Regards!