Home > Software design >  C# Custom Class(server user) in WCF service not working in client(but struct work)(problem)
C# Custom Class(server user) in WCF service not working in client(but struct work)(problem)

Time:05-22

//I have wcf service is hosted by the console application. console app

  using System.ServiceModel;
 using System.Text;
 using System.Threading.Tasks;

   namespace ConsoleApp1
 {
   class Program
   {
    static void Main(string[] args)
    {
        try
        {
            using (var host = new ServiceHost(typeof(ClassLibrary1.wcf_chating)))
            {

                host.Open();
                Console.WriteLine("Стартуем!");
                Console.ReadLine();

            }
        }
        catch (Exception ex)
        {
            
            Console.WriteLine($"Исключение: {ex.Message}");
            Console.WriteLine($"Исключение: {ex.InnerException}");
            Console.WriteLine($"Исключение: {ex.TargetSite}");
            Console.WriteLine($"Исключение: {ex.Source}");
            Console.WriteLine($"Исключение: {ex.StackTrace}");
            Console.ReadLine();
        }
    }
}

}

//contract hosted in console

    using System;
    using System.Collections.Generic;
    using System.Linq;
     using System.Runtime.Serialization;
     using System.ServiceModel;
     using System.Text;
     using MySql.Data.MySqlClient;
     namespace ClassLibrary1
    {

[ServiceContract(CallbackContract =typeof(i_call_back))]
[ServiceKnownType(typeof(ServerUser))]
public interface Iwcf_chating
{     

    [OperationContract]
    void connect(string name, int ID);
    [OperationContract]
   
    void disconnect(int id);
    [OperationContract(IsOneWay =true)]
    void senmessage(String msg,int id);
    
}
public interface i_call_back
{
    [OperationContract(IsOneWay = true)]
    void mescallback(String msg);   
}
[ServiceContract(CallbackContract =typeof(i_call_back2))]
public interface Idatabase
{
    [OperationContract]
   void dataconnect();
    
    [OperationContract]
    DataUser Checproverka1(String text1, String  text2);
    [OperationContract]
    DataUser Checproverka2(String text1);
    [OperationContract]
    void insertresults(String text1, String text2, String text3, String text4);
   !!!! [OperationContract](problem metod because return custom class if i only delete this 
     metod i can connect with my client application )
    List<ServerUser> Online_Vivod();
   }
  public interface i_call_back2
  {
    [OperationContract(IsOneWay = true)]       
    void mescallback2(String name);
  }  
 }

//app.config file

 <?xml version="1.0" encoding="utf-8"?>
<configuration>
 <startup>
 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
 </startup>
 <system.serviceModel>
 <behaviors>
  <serviceBehaviors>
    <behavior name="gametime">
      <serviceMetadata httpGetEnabled="true"/>      
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service name="ClassLibrary1.wcf_chating" behaviorConfiguration="gametime">       
    <endpoint address="" binding="netTcpBinding" contract="ClassLibrary1.Idatabase">
    </endpoint>
    <endpoint address="" binding="wsDualHttpBinding" contract="ClassLibrary1.Iwcf_chating">
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses>           
        <add baseAddress="http://192.168.1.65:8302" />
        <add baseAddress="net.tcp://192.168.1.65:8301" />
      </baseAddresses>
    </host>
  </service>
   </services>
    </system.serviceModel>
  <runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" 
     publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.5.0" newVersion="4.0.5.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" 
    culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
  </dependentAssembly>
 </assemblyBinding>
  </runtime>
  </configuration>

//file have custom class and struct(client see struct but cant see my class)

      using System;
      using System.Collections.Generic;
      using System.Linq;
       using System.Text;
      using System.Threading.Tasks;
      using System.ServiceModel;
      using System.Runtime.Serialization;

    namespace ClassLibrary1
  { 
[DataContract]
public class ServerUser
{
    [DataMember]
    public int ID { get; set; }
    [DataMember]
    public string name { get; set; }
    [DataMember]
    public OperationContext operationContext { get; set; }

    public ServerUser(OperationContext operationContext, string name, int Id)
    {


        this.operationContext = operationContext;
        this.name = name;
        this.ID = Id;
    }
    public ServerUser()
    {

    }

}
[DataContract]
public struct DataUser
{
    [DataMember]
    public string msg;
    [DataMember]
    public string name;
    [DataMember]
    public int Id;
    public DataUser(string msg,string name,int Id)
    {
        this.msg = msg;
        this.name = name;
        this.Id = Id;
    }              
   }
    }

//error error visual studio Произошла ошибка при загрузке ''http://localhost:8302/$metadata''. Отказ при выполнении запроса с состоянием HTTP 400: Bad Request.now allow metod...

settings connect connect wcf in client settings

//servic interface and struct is auto generated by Service in client i guess but i dont see my class in client auto generate file. Server success compile but cant connect with my client when i return custom class //i show you part auto file too

  namespace WindowsFormsApp12.ChatService {
   using System.Runtime.Serialization;
   using System;   
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
  [System.Runtime.Serialization.DataContractAttribute(Name="DataUser", 
   Namespace="http://schemas.datacontract.org/2004/07/ClassLibrary1")]
     [System.SerializableAttribute()]
     public partial struct DataUser : System.Runtime.Serialization.IExtensibleDataObject, 
      System.ComponentModel.INotifyPropertyChanged {
    
    [System.NonSerializedAttribute()]
    private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
    
    [System.Runtime.Serialization.OptionalFieldAttribute()]
    private int IdField;
    
    [System.Runtime.Serialization.OptionalFieldAttribute()]
    private string msgField;
    
    [System.Runtime.Serialization.OptionalFieldAttribute()]
    private string nameField;
    
    public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
        get {
            return this.extensionDataField;
        }
        set {
            this.extensionDataField = value;
        }
    }
    
    [System.Runtime.Serialization.DataMemberAttribute()]
    public int Id {
        get {
            return this.IdField;
        }
        set {
            if ((this.IdField.Equals(value) != true)) {
                this.IdField = value;
                this.RaisePropertyChanged("Id");
            }
        }
    }
    
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string msg {
        get {
            return this.msgField;
        }
        set {
            if ((object.ReferenceEquals(this.msgField, value) != true)) {
                this.msgField = value;
                this.RaisePropertyChanged("msg");
            }
        }
    }
    
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            if ((object.ReferenceEquals(this.nameField, value) != true)) {
                this.nameField = value;
                this.RaisePropertyChanged("name");
            }
        }
    }
    
    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    
    void RaisePropertyChanged(string propertyName) {
        System.ComponentModel.PropertyChangedEventHandler propertyChanged = 
       this.PropertyChanged;
        if ((propertyChanged != null)) {
            propertyChanged(this, new 
     System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }
     }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ChatService.Idatabase", 
      CallbackContract=typeof(WindowsFormsApp12.ChatService.IdatabaseCallback))]
       public interface Idatabase {

       [System.ServiceModel.OperationContractAttribute(Action="http://temp 
       uri.org/Idatabase/dataconnect", 
              ReplyAction="http://tempuri.org/Idatabase/dataconnectResponse")]
    void dataconnect();
    
    [

............

CodePudding user response:

Ok,i find my problem App.config file, base addres

    <?xml version="1.0" encoding="utf-8" ?>
     <configuration>
    <startup>
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
      </startup>
    <system.serviceModel>
      <services>
    <service name="ClassLibrary1.wcf_chating" behaviorConfiguration="BehConfig">
    <endpoint contract="ClassLibrary1.Iwcf_chating" binding="wsDualHttpBinding" 
     address=""/>
    <endpoint contract="ClassLibrary1.Idatabase" binding="wsDualHttpBinding" 
     address=""/>
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" 
     address="mex"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:4000"/>
      </baseAddresses>
    </host>
    </service>
     </services>
      <behaviors>
    <serviceBehaviors>
    <behavior name="BehConfig" >
      <serviceMetadata httpGetEnabled="true" />
    </behavior>
     </serviceBehaviors>
      </behaviors>
       </system.serviceModel>
    </configuration>
  • Related