2012-06-06 3 views
0


У меня проблема с WCF.
Первое приложение я написал пример с сайта this. Это сработало хорошо.
Мне нужно сделать приложение для переноса объектов из списка серверов из базы данных. Но когда я получаю список клиентов, следующие CommunicationException:CommunicationException. WCF

Ошибка при получении ответа HTTP (localhost: 8080). Это может быть связано с привязкой конечной точки службы, не использующей протокол HTTP. Это также может быть связано с тем, что сервер HTTP-запроса прерывается (возможно, из-за отключения службы). Для получения более подробной информации см. Журналы сервера.

Сервер работал хорошо, или я ничего не понимаю.
Если вам нужна информация (код) о проекте, я дам его


Извините за мой английский.

UPD: конфигурации:

<?xml version="1.0"?> 
<configuration> 
    <system.serviceModel> 
    <services> 
     <service name="Habra.Server.MobilePosts" behaviorConfiguration="MyBehavior"> 
     <endpoint 
      address="" 
      binding="basicHttpBinding" 
      contract="Habra.Core.IMobilePosts" /> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="MyBehavior"> 
      <serviceMetadata httpGetEnabled="True"/> 
      <serviceDebug includeExceptionDetailInFaults="true"/> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    </system.serviceModel> 
    <runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <dependentAssembly> 
     <assemblyIdentity name="Castle.Core" publicKeyToken="407dd0808d44fbdc" culture="neutral" /> 
     <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> 
     </dependentAssembly> 
    </assemblyBinding> 
    </runtime> 
</configuration> 

код сервера:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Habra.Server 
{ 
    using System.ServiceModel; 

    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      Type serviceType = typeof(MobilePosts); 
      Uri serviceUri = new Uri("http://localhost:8080/"); 
      ServiceHost host = new ServiceHost(serviceType, serviceUri); 
      host.Open(); 

      foreach (Uri uri in host.BaseAddresses) 
      { 
       Console.WriteLine("\t{0}", uri.ToString()); 
      } 

      Console.WriteLine(); 
      Console.WriteLine("Number of dispatchers listening : {0}", host.ChannelDispatchers.Count); 
      foreach (System.ServiceModel.Dispatcher.ChannelDispatcher dispatcher in host.ChannelDispatchers) 
      { 
       Console.WriteLine("\t{0}, {1}", dispatcher.Listener.Uri.ToString(), dispatcher.BindingName); 
      } 

      Console.WriteLine(); 
      Console.WriteLine("Press <ENTER> to terminate Host"); 
      Console.ReadLine(); 
     } 
    } 
} 

UPD2:
терпит неудачу в:

MobilePostsClient mpc = new MobilePostsClient(); 
var list = mpc.GetAllPosts(); 

MobilePostClient создан Add Service Reference.

UPD3: IMobilePosts:

[ServiceContract] 
public interface IMobilePosts 
{ 
    [OperationContract] 
    List<Post> GetAllPosts(); 

    [OperationContract] 
    FullPost GetFullPost(int postId); 
} 

MobilePosts:

public class MobilePosts : IMobilePosts 
{ 
    private readonly IRepository repository = new RepositoryQueries(); 

    public List<Post> GetAllPosts() 
    { 
     var list = this.repository.GetAllPosts(); 

     foreach (Post post in list) 
     { 
      Console.WriteLine(post.Title + " loading..."); 
     } 

     return list; 
    } 

    public FullPost GetFullPost(int postId) 
    { 
     return this.repository.GetFullPostById(postId); 
    } 
} 

Хранилища работал правильно.

+1

Вы можете разместить код сервиса и конфигурации? – devlife

+0

Вы можете показать, в какой момент это происходит? и конфигурационный файл для вашего сервиса? – Chris

+0

@devlife Вы спросили меня об этом? – LuckSound

ответ

1

Вы установили атрибуты для свойств класса Post?

[DataContract] 
public class Post 
{ 
    [DataMember] 
    public string Post{get;set;} 

Вы можете отслеживать все сообщения с ServiceBehavior read more here.
т.е. положить приписывать Сервье

[SilverlightFaultAttribute] 
public class MobilePosts : IMobilePosts   
{...} 

и set trace output to file

using System; 
using System.Diagnostics; 
using System.IO; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Channels; 
using System.ServiceModel.Description; 
using System.ServiceModel.Dispatcher; 
using System.Xml; 

namespace Wcf 
{ 
public class SilverlightFaultAttribute : Attribute, IServiceBehavior 
{ 
    #region IServiceBehavior Members 

    public void AddBindingParameters(ServiceDescription serviceDescription, 
     ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, 
     BindingParameterCollection bindingParameters) 
    { 

    } 

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
     Trace.WriteLine(" */*/*/* ApplyDispatchBehavior"); 

     foreach (var t in serviceHostBase.ChannelDispatchers) 
     { 
      var channelDispatcher = t as ChannelDispatcher; 
      if ((channelDispatcher == null)) continue; 
      foreach (var dispatcher2 in channelDispatcher.Endpoints) 
      { 
       var dispatchRuntime = dispatcher2.DispatchRuntime; 
       dispatchRuntime.MessageInspectors.Add(new SilverlightFaultMessageInspector()); 
      } 
     } 
    } 
    public class SilverlightFaultMessageInspector : IDispatchMessageInspector 
    { 
     public void BeforeSendReply(ref Message reply, object correlationState) 
     { 
      if (reply.IsFault) 
      { 
       Trace.WriteLine(" */*/*/* reply.IsFault"); 
       Trace.WriteLine(reply); 
       var property = new HttpResponseMessageProperty(); 

       // Here the response code is changed to 200. 
       property.StatusCode = System.Net.HttpStatusCode.OK; 

       reply.Properties[HttpResponseMessageProperty.Name] = property; 

       MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue); 
       Message copy = buffer.CreateMessage(); // Create a copy to work with 
       reply = buffer.CreateMessage();   // Restore the original message 

       object faultDetail = ReadFaultDetail(copy); 
       Exception exception = faultDetail as Exception; 
       Trace.WriteLine(exception); 
      } 
     } 

     public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) 
     { 
      // Do nothing to the incoming message. 
      return null; 
     } 

     private static object ReadFaultDetail(Message reply) 
     { 
      const string detailElementName = "Detail"; 
      using (XmlDictionaryReader reader = reply.GetReaderAtBodyContents()) 
      { 
       // Find <soap:Detail> 
       while (reader.Read()) 
       { 
        if (reader.NodeType == XmlNodeType.Element && reader.LocalName == detailElementName) 
        { 
         break; 
        } 
       } 

       // Did we find it? 
       if (reader.NodeType != XmlNodeType.Element || reader.LocalName != detailElementName) 
       { 
        return null; 
       } 
       // Move to the contents of <soap:Detail> 
       if (!reader.Read()) 
        return null; 
       // Deserialize the fault 
       NetDataContractSerializer serializer = new NetDataContractSerializer(); 
       try 
       { 
        return serializer.ReadObject(reader); 
       } 
       catch (FileNotFoundException) 
       { 
        // Serializer was unable to find assembly where exception is defined 
        return null; 
       } 
      } 
     } 
    } 

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
    } 

    #endregion 
} 
} 
Смежные вопросы