2015-08-10 5 views
0

Я создаю службу поддержки WCF с использованием этого tuto и подключаю его к базе данных SQL-сервера для получения данных, и эта служба была создана, и она работает, но проблема не может найти элемент конечной точки это мой код EventDataContractВеб-служба WCF не может найти элемент конечной точки

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.Web; 

namespace WCFEventsSchedule 
{ 
    [DataContract] 
    public class EventDataContract 
    { 
     [DataMember] 
     public int EventID { get; set; } 
     [DataMember] 
     public string Text { get; set; } 
     [DataMember] 
     public DateTime Start_Date { get; set; } 
     [DataMember] 
     public DateTime End_Date { get; set; } 
     [DataMember] 
     public int Room_Id { get; set; } 
     [DataMember] 
     public int User_Id { get; set; } 
    } 
} 

IEventService

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Web; 
using System.Text; 

namespace WCFEventsSchedule 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IEventService" in both code and config file together. 
    [ServiceContract] 
    public interface IEventService 
    { 
     [OperationContract] 
     [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, 
      ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetAllEvents/")] 
     List<EventDataContract> GetAllEvent(); 

     [OperationContract] 
     [WebGet(RequestFormat = WebMessageFormat.Json, 
      ResponseFormat = WebMessageFormat.Json, 
      UriTemplate = "/EventDetails/{EventID}")] 
     EventDataContract EventDetails(string EventID); 
    } 
} 

EventService.svc

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.Text; 
using WCFEventsSchedule.Model; 

namespace WCFEventsSchedule 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "EventService" in code, svc and config file together. 
    // NOTE: In order to launch WCF Test Client for testing this service, please select EventService.svc or EventService.svc.cs at the Solution Explorer and start debugging. 
    public class EventService : IEventService 
    { 
     SchedulerEntities se; 
     public EventService() 
     { 
      se = new SchedulerEntities(); 
     } 

     public List<EventDataContract> GetAllEvent() 
     { 
      var query = (from a in se.Events 
         select a).Distinct(); 

      List<EventDataContract> EventList = new List<EventDataContract>(); 

      query.ToList().ForEach(x => 
      { 
       EventList.Add(new EventDataContract 
       { 
        EventID = x.id, 
        Text = x.text, 
        Start_Date = x.start_date, 
        End_Date = x.end_date, 
        Room_Id = (int) x.room_id, 
        User_Id = (int) x.user_id, 
       }); 
      }); 
      return EventList; 
     } 

     public EventDataContract EventDetails(string EventID) 
     { 
      EventDataContract even = new EventDataContract(); 
      try 
      { 
       var query = (from a in se.Events 
          where a.id.Equals(EventID) 
          select a).Distinct().FirstOrDefault(); 
       even.EventID = query.id; 
       even.Text = query.text; 
       even.Start_Date = query.start_date; 
       even.End_Date = query.end_date; 
       even.Room_Id = (int) query.room_id; 
       even.User_Id = (int) query.user_id; 
      } 
      catch (Exception ex) 
      { 
       throw new FaultException<string>(ex.Message); 
      } 
      return even; 
     } 
    } 
} 

Web.config

<?xml version="1.0" encoding="utf-8"?> 
<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> 
    <appSettings> 
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> 
    </appSettings> 
    <system.web> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" /> 
    </system.web> 
    <system.serviceModel> 
    <services> 
     <service name="WCFEventsSchedule.EventService" behaviorConfiguration="serviceBehavior" > 
     <endpoint address="" 
        binding="webHttpBinding" 
        contract="WCFEventsSchedule.IEventService" 
        behaviorConfiguration="web"> 

     </endpoint> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="serviceBehavior"> 
      <!-- To avoid disclosing metadata information, set the values below to false before deployment --> 
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> 
      <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> 
      <serviceDebug includeExceptionDetailInFaults="false" /> 
     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior name="web"> 
      <webHttp/> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <protocolMapping> 
     <add binding="webHttpBinding" scheme="https" /> 
    </protocolMapping> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true" /> 
    <!-- 
     To browse web app root directory during debugging, set the value below to true. 
     Set to false before deployment to avoid disclosing web app folder information. 
     --> 
    <directoryBrowse enabled="true" /> 
    </system.webServer> 
    <connectionStrings> 
    <add name="SchedulerEntities" connectionString="metadata=res://*/Model.EventsModel.csdl|res://*/Model.EventsModel.ssdl|res://*/Model.EventsModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Scheduler.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    </connectionStrings> 
    <entityFramework> 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> 
     <parameters> 
     <parameter value="mssqllocaldb" /> 
     </parameters> 
    </defaultConnectionFactory> 
    <providers> 
     <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
    </providers> 
    </entityFramework> 
</configuration> 

Моя таблица События

CREATE TABLE [dbo].[Events] (
    [id]   INT  IDENTITY (1, 1) NOT NULL, 
    [text]  TEXT  COLLATE Cyrillic_General_CI_AS NULL, 
    [start_date] DATETIME NOT NULL, 
    [end_date] DATETIME NOT NULL, 
    [room_id] INT  NULL, 
    [user_id] INT  NULL, 
    CONSTRAINT [PK_Events] PRIMARY KEY CLUSTERED ([id] ASC) 
); 

и позже я покажу, что данные на Windows Form Application с использованием WCF ,

обновлена ​​Fater ошибка добавления [ServiceBehavior (IncludeExceptionDetailInFaults = TRUE)]

Le serveur a rencontré une erreur lors du traitement de la demande. Le message d'exception est 'Un objet qui autorise la valeur Null doit posséder une valeur.'. Pour plus d'informations, consultez les journaux du serveur. La trace de la pile d'exception est : 

à System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) à System.Nullable`1.get_Value() à WCFEventsSchedule.EventService.<>c__DisplayClass2.<GetAllEvent>b__1(Events x) dans c:\Users\juste 3al faza\Desktop\Scheduler.MVC5\WCFEventsSchedule\EventService.svc.cs:ligne 31 à System.Collections.Generic.List`1.ForEach(Action`1 action) à WCFEventsSchedule.EventService.GetAllEvent() dans c:\Users\juste 3al faza\Desktop\Scheduler.MVC5\WCFEventsSchedule\EventService.svc.cs:ligne 29 à SyncInvokeGetAllEvent(Object , Object[] , Object[]) à System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) à System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) à System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) à System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) à System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) à System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) à System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) à System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) à System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) à System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) à System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet) 
+1

, что сообщение, которое вы видите, когда вы посещаете URL HTTP: // localhost: portNo/GetAllEvents/ –

+0

На сервере возникла ошибка при обработке запроса. Для получения дополнительной информации проверьте журналы сервера. – Amin

ответ

1

Эта проблема возникает при изображении любой проблемы в службе WCF. Так что, пожалуйста, просмотрите более подробную информацию о проблеме, вам нужно указать includeexceptiondetailInfaults атрибут true в теге servicedebug.

EDIT

для тех, кто не понимают французский вот что ошибка приводит к

Сервер обнаружил ошибку при обработке запроса. Сообщение об ошибке : «Объект, для которого значение nullable должно иметь значение. ' . Для получения дополнительной информации проверьте журналы сервера. Трассировки стека исключений является :

System.ThrowHelper.ThrowInvalidOperationException (ExceptionResource ресурсов) для System.Nullable1.get_Value(), чтобы WCFEventsSchedule.EventService. <> c__DisplayClass2.< GetAllEvent> b__1 (События х)

Это означает, что в вашем GetAllEvent() вы пытаетесь присвоить нулевое значение. Если поставить отладчик в этот момент вы можете узнать, какую линию бросает исключение,

(Подсказка: его в основном те ценности, которые не должны быть NULL)

+0

Я обновил свою проблему с ошибкой после добавления includeeexceptiondetailInfaults – Amin

+0

вот и все, 2 последних значения возвращены null, я прокомментировал это, и он работает – Amin

1

Я не уверен, что этот вопрос, но я подозреваю, что у вас есть проблема с файлом web.config.

Прочитайте this tutorial для получения более четкого обзора.

На нем четко показаны две части web.config, которые вам нужно будет изменить, чтобы это правильно работало.

+0

они выглядят одинаково – Amin