在 WCF 服务上的 AJAX REST 请求期间启用 CORS 中的 OPTIONS 方法

rea*_*leo 2 ajax wcf cors angular

我已经挠了 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

将此自定义扩展添加到 app.config 文件解决了我的 CORS 问题。我当前的问题是每当我发出 POST 请求时,我都会收到错误消息:

Request Method:OPTIONS
Status Code:405 Method Not Allowed
Run Code Online (Sandbox Code Playgroud)

我对 C# 很陌生,我似乎无法找到放置代码的位置,这将使我能够解决这个问题。我有一个想法,它应该放在 BeforeSendReply() 方法中的某个地方。请帮我!我真的会很感激的!

问候!

rea*_*leo 6

我想出了解决方案,我希望这可以帮助遇到同样问题的每个人。在CustomHeaderMessageInspector我在问题中发布的课程中,我在方法中编辑了以下代码,AfterReceiveRequest如下所示:

// return null;
var httpRequest = (HttpRequestMessageProperty)request
    .Properties[HttpRequestMessageProperty.Name];
return new
{
    origin = httpRequest.Headers["Origin"],
    handlePreflight = httpRequest.Method.Equals("OPTIONS",
    StringComparison.InvariantCultureIgnoreCase)
};
Run Code Online (Sandbox Code Playgroud)

我希望代码所做的是使用 OPTIONS 方法监视任何请求,并用预检状态“标记”它。然后我修改了中的代码,BeforeSendReply如下所示:

var state = (dynamic)correlationState;
if (state.handlePreflight)
{
    reply = Message.CreateMessage(MessageVersion.None, "PreflightReturn");

    var httpResponse = new HttpResponseMessageProperty();
    reply.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);

    httpResponse.SuppressEntityBody = true;
    httpResponse.StatusCode = HttpStatusCode.OK;
}

var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
foreach (var item in requiredHeaders)
{
    httpHeader.Headers.Add(item.Key, item.Value);
}
Run Code Online (Sandbox Code Playgroud)

这样做(我希望)是获取任何带有 OPTIONS 标记的请求并通过返回 200 状态代码来处理它。这让它终于工作了,我希望它可以帮助某人!