CORS на самостоятельной службе WCF - PullRequest
0 голосов
/ 08 марта 2019

Я пытаюсь внедрить поддержку CORS в мою службу WCF.

Я получил несколько кодов от

https://enable -cors.org / server_wcf.html

public class CustomHeaderMessageInspector : IDispatchMessageInspector
        {
            Dictionary<string, string> requiredHeaders;
            public CustomHeaderMessageInspector (Dictionary<string, string> headers)
            {
                requiredHeaders = headers ?? new Dictionary<string, string>();
            }

            public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
            {
                return null;
            }

            public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
                foreach (var item in requiredHeaders)
                {
                    httpHeader.Headers.Add(item.Key, item.Value);
                }           
            }
        }

Но я получаю сообщение об ошибке в этой строке

public class CustomHeaderMessageInspector : IDispatchMessageInspector

ОШИБКА: Классы могут наследоваться только от других классов

Какмогу ли я наследовать IDispatchMessageInspector

Спасибо

1 Ответ

0 голосов
/ 11 марта 2019

Я сделал демо, желаю, чтобы он был вам полезен.
Справка.

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;

Сервер.

class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost sh = new ServiceHost(typeof(MyService)))
            {
                sh.Open();
                Console.WriteLine("service is ready...");
                Console.ReadLine();
                sh.Close();
            }

        }
    }
    [ServiceContract(Namespace = "mydomain")]
    public interface IService
    {
        [OperationContract]
        [WebGet(ResponseFormat =WebMessageFormat.Json)]
        string SayHello();
    }
    public class MyService : IService
    {
        public string SayHello()
        {
            return $"Hello, busy World,{DateTime.Now.ToShortTimeString()}";
        }
    }
    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, IClientChannel channel, InstanceContext instanceContext)
        {
            string displayText = $"Server has received the following message:\n{request}\n";
            Console.WriteLine(displayText);
            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);
            }

            string displayText = $"Server has replied the following message:\n{reply}\n";
            Console.WriteLine(displayText);

        }
    }
    public class CustomContractBehaviorAttribute : BehaviorExtensionElement, IEndpointBehavior
    {
        public override Type BehaviorType => typeof(CustomContractBehaviorAttribute);

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, 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)
        {

        }


        protected override object CreateBehavior()
        {
            return new CustomContractBehaviorAttribute();
        }
    }

App.config

<system.serviceModel>
    <services>
      <service name="Server3.MyService" behaviorConfiguration="mybahavior">
        <endpoint address="" binding="webHttpBinding" contract="Server3.IService" behaviorConfiguration="rest"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:5638"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mybahavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="rest">
          <webHttp />
          <CorsBehavior />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add name="CorsBehavior" type="Server3.CustomContractBehaviorAttribute, Server3" />
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>

Клиент.

    <script>
    $(function(){
        $.ajax({
            method:"Get",
            url: "http://10.157.13.69:5638/sayhello",
            dataType:"json",
            success: function(data){
                $("#main").html(data);
            }
        })
    })
</script>

Результат
enter image description here
Не стесняйтесь, дайте мне знать, если я могу чем-то помочь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...