简体   繁体   English

WCF c#中自定义类的传输问题

[英]Problems with the transfer of custom class in WCF c#

I am transferring data between a server and a client. 我正在服务器和客户端之间传输数据。 The client easily receives the usual data types such as int from the server, but if you pass a custom class to it, then I get the following exception: 客户端很容易从服务器接收常规数据类型,例如int ,但是如果将自定义类传递给它,那么我将收到以下异常:

System.ServiceModel.CommunicationException: An error occurred while getting the HTTP response to http://127.0.0.1:8000/Service . System.ServiceModel.CommunicationException:获取HTTP响应http://127.0.0.1:8000/Service时发生错误。 This is probably caused by the fact that the service endpoint binding does not use the HTTP protocol. 这可能是由于服务端点绑定未使用HTTP协议这一事实造成的。 This may also be caused by the fact that the HTTP request context has been interrupted by the server (possibly due to the service being disabled). 这也可能是由于HTTP请求上下文已被服务器中断(可能是由于服务被禁用)所致。 See the server logs for details. 有关详细信息,请参见服务器日志。

I tried many solutions to solve such problems, but nothing helped. 我尝试了许多解决方案来解决此类问题,但没有任何帮助。 I added getters and setters to class fields, changed DataContract , etc to Serializable : 我在类字段中添加了getter和setter方法,将DataContract等更改为Serializable

Custom Class 自定义类

    namespace c_CardStrategy
{
    [DataContract]
    public class Card
    {
        #region ПОЛЯ
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Effect { get; set; }
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public int Price { get; set; }
        [DataMember]
        public string EffText { get; set; }
        #endregion
        #region Конструктор
        public Card(int id, string name, string effect, int price, string efftext)
        {
            Price = price;
            ID = id;
            Name = name;
            Effect = effect;
            EffText = efftext;
        }
        public Card()
        {
            Name = "";
            Effect = "";
            ID = 0;
            Price = 0;
            EffText = "";
        }
        #endregion
    }

    [DataContract]
    public class Moster_Card : Card
    {
        [DataMember]
        public int? Health { get; set; }
        [DataMember]
        public int? Power { get; set; }

        public Moster_Card(int id, string name, int? health, int? power, string effect, int price, string efftext) : base(id, name, effect, price, efftext)
        {
            Health = health;
            Power = power;
        }
        public Moster_Card()
        {
            Name = "";
            Effect = "";
            ID = 0;
            Price = 0;
            EffText = "";
            Health = 0;
            Power = 0;
        }
    }

    [DataContract]
    public class Spell_Card : Card
    {
        [DataMember]
        public int? Charge { get; set; }

        public Spell_Card(int id, string name, string effect, int price, string efftext, int? charge) : base(id, name, effect, price, efftext)
        {
            Charge = charge;
        }
        public Spell_Card()
        {
            Name = "";
            Effect = "";
            ID = 0;
            Price = 0;
            EffText = "";
            Charge = 0;
        }
    }


}



Interface 接口

    [ServiceContract]
        public interface IGame
        {
            [OperationContract]
            Players GetPlayer(int grid);

            [OperationContract]
            List<Players> Players();

            [OperationContract]
            int GetTurn(int GameGrid);

            [OperationContract]
            void FindGame(Players Player);

            [OperationContract]
            object GetAllCards();

            [OperationContract]
            List<Card> GetDeckOnCode(string code_deck);

            [OperationContract]
            bool Checkuser(string login, string pass);

            [OperationContract]
            void WriteInLog(string Text);
        }


Server 服务器

    namespace c_CardStrategy
    {
        [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
        public class GameServer : IGame
        {
            private List<Players> listPlayers;
            private List<Game> Games;
            public hpartner_cgEntities context;
            ...
            public object GetAllCards()
            {
                context = new hpartner_cgEntities();
                List<Card> Cards = new List<Card>();
                foreach(var Card in context.Cards)
                {
                    int id = Card.Card_id;
                    string name = Card.Card_name;
                    int f = Card.Card_eff_id;
                    string eff;
                    switch (f)
                    {
                        case 0:
                            eff = "None";
                            break;
                        case 1:
                            eff = "Taunt";
                            break;
                        case 2:
                            eff = "Charge";
                            break;
                        default:
                            eff = "None";
                            break;
                    }
                    int price = Card.Card_price;
                    string efftext = Card.Card_eff_text;
                    int? Health = Card.Card_health;
                    int? Power = Card.Card_power;
                    int? Charge = Card.Charge;
                    if (Health != null)
                    {
                        Cards.Add(new Spell_Card(id, name, eff, price, efftext, Charge));
                    }
                    else
                    {
                        Cards.Add(new Moster_Card(id, name, Health, Power, eff, price, efftext));
                    }
                }
                return Cards;
            }
            ...
    }
    }

Client 客户

    public partial class DecksWindow : Window
        {
            private GameClient Client;
            public DecksWindow(GameClient client)
            {
                InitializeComponent();
                Client = client;
            }

            private void New_deck_Click(object sender, RoutedEventArgs e)
            {
                Deck_list.Visibility = Visibility.Visible;
                List<Card> Cards = new List<Card>();
                try
                {
                    Cards = Client.GetAllCards() as List<Card>;
                    foreach (Card Card in Cards)
                    {
                        StackPanel Sp = new StackPanel();
                        Sp.Height = 170;
                        Sp.Width = 150;
                        Sp.Margin = new Thickness(0, 5, 5, 0);
                        Sp.Background = Brushes.Red;
                        Sp.Tag = Card.IDk__BackingField.ToString();
                        Sp.Uid = 2.ToString();
                        Deck_list.Children.Add(Sp);
                    }
                }
                catch (Exception ex)
                {
                    tb.Text += ex.Message;
                }
                //tb.Text = Client.Checkuser("Admin", "Admin").ToString();

            }
        }

config Client 配置客户端

    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
      </startup>
      <entityFramework>
        <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
        <providers>
          <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework" />
        </providers>
      </entityFramework>
      <connectionStrings>
        <add name="hpartner_cgEntities" providerName="System.Data.EntityClient" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=hpartnerlink.ru;user id=hpartner;password=M7gn46Wx3b;persistsecurityinfo=True;database=hpartner_cg&quot;" />
      </connectionStrings>
      <system.web>
        <httpRuntime maxRequestLength="262144"  executionTimeout="103600"/>
      </system.web>
      <system.serviceModel>
        <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBinding_IGame" />
            <binding name="BasicHttpBinding_IGame1" />
          </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address="http://127.0.0.1:8000/Service" binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_IGame" contract="GameServiceReference.IGame"
            name="BasicHttpBinding_IGame" />
          <endpoint address="http://0.0.0.0:8000/Service" binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_IGame1" contract="ServiceReference1.IGame"
            name="BasicHttpBinding_IGame1" />
        </client>
      </system.serviceModel>

Config Server 配置服务器

    <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
      </startup>
      <entityFramework>
        <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
        <providers>
          <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework" />
        </providers>
      </entityFramework>
      <connectionStrings>
        <add name="hpartner_cgEntities" providerName="System.Data.EntityClient" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=hpartnerlink.ru;user id=hpartner;password=M7gn46Wx3b;persistsecurityinfo=True;database=hpartner_cg&quot;" />
      </connectionStrings>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior name="debug">
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <services>
          <service name="MyServiceName" behaviorConfiguration="debug" />
        </services>
      </system.serviceModel>

Can you access the WSDL of the web service after you host the service? 托管服务后可以访问Web服务的WSDL吗? I doubt that the configuration may be too simple. 我怀疑配置可能太简单了。 I suggest you apply the below configuration on the server side. 我建议您在服务器端应用以下配置。

  <system.serviceModel>
    <services>
      <service name="YourNamespace.GameServer " behaviorConfiguration="mybehavior">
        <endpoint address="http://localhost:8000/Service" binding="basicHttpBinding" contract="YourNamespace.IGame " ></endpoint>
        <endpoint address="http://localhost:8000/Service/mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>
    </services>    
    <behaviors>
      <serviceBehaviors>
        <behavior name="mybehavior">
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

After we host the service, thereby we could access the service information by typing the service address in the browser address bar. 托管服务后,我们可以通过在浏览器地址栏中键入服务地址来访问服务信息。

http://localhost:8000/service

Besides, we may need administrative privilege when hosting the service. 此外,托管服务时,我们可能需要管理特权。 Feel free to let me know if the problem still exists. 随时让我知道问题是否仍然存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM