У меня проблема с получением объекта из службы WCF.Я создал проект WCF и проект Silverlight.В SQL Express у меня есть база данных с двумя таблицами: QuestionSet и AnswerSet.
Итак, в проекте WCF я добавил свою модель базы данных, добавив новый элемент, ADO.NET Entity Data Model.Затем я создал оттуда элемент генерации кода (ADO.NET DbContext Generator).(Я использую Entity Framework 4.1).
При этом создаются три класса в Context.tt, AnswerSet, QuestionSet и Context.cs
класс QuestionSet выглядит следующим образом:
public partial class QuestionSet
{
public QuestionSet()
{
this.AnswerSets = new HashSet<AnswerSet>();
}
public int Id { get; set; }
public string Quest { get; set; }
public virtual ICollection<AnswerSet> AnswerSets { get; set; }
}}
Моя служба выглядит так:
QuestionnairedbEntities db = new QuestionnairedbEntities();
public MyOwnClass DoWork()
{
MyOwnClass n = new MyOwnClass ();
n.Name = "Name of the Class";
return n;
}
public QuestionSet DoWorkQuest()
{
QuestionSetDTO qsd = new QuestionSetDTO();
return db.QuestionSets.Find(11);
}
, и когда я сейчас запускаю службу, запускается тестовый клиент WCF.Метод doWork отлично работает с моим собственным классом.но другой метод, doWorkQuest не работает.это работает, когда я изменяю возвращаемое значение на класс DTO и приведу это .. но почему не работает с сущностью, созданной из базы данных ??..
это ошибка, которую показывает клиент wcf:
Не удалось вызвать службу.Возможные причины: служба недоступна или недоступна;конфигурация на стороне клиента не соответствует прокси;существующий прокси-сервер недействителен.Обратитесь к трассировке стека для более подробной информации.Вы можете попытаться выполнить восстановление, запустив новый прокси-сервер, восстановив конфигурацию по умолчанию или обновив службу.
Базовое соединение было закрыто: соединение было неожиданно закрыто.
Трассировка стека сервера: atSystem.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException (WebException WebException, HttpWebRequest запрос, HttpAbortReason abortReason)
в System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply (TimeSpan тайм-аут) в System.ServiceModel.Channels.RequestChannel.Request(Сообщение-сообщение, время ожидания TimeSpan) в System.ServiceModel.Dispatcher.RequestChannelBinder.Request (сообщение-сообщение, время ожидания TimeSpan) в System.ServiceModel.Channels.ServiceChannel.Call (действие String, логическое oneway, операция ProxyOperationRuntime, объект Object [] ins,[] ауты, тайм-аут TimeSpan) в System.ServiceModel.Channels.ServiceChannelProxy.InvokeService (IMethodCallMessage methodCall, ProxyOperationRuntime operation) в System.ServiceModel.Channels.ServiceChannelProxy.Invoke (сообщение IMessage)
Исключение перебрасывается в [0]: в System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage (запрос IMessage System RegMsg, IMessage).Runtime.Remoting.Proxies.RealProxy.PrivateInvoke (MessageData & msgData, тип Int32) в INeuralnetworkService.DoWorkQuest () в NeuralnetworkServiceClient.DoWorkQuest ()
Внутреннее исключение: было закрыто непредвиденное соединение.в System.Net.HttpWebRequest.GetResponse () в System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply (TimeSpan timeout)
мне кто-нибудь может помочь?
@ Джон Сондерс, спасибо за ваш ответ.Я взглянул на окно просмотра событий Windows.
Итак, ошибка в том, что ASP-совместимость включена, я должен выключить или разрешить или запросить :) см. сообщение:
$
The service cannot be activated because it requires ASP.NET compatibility.
ASP.NET compatibility is not enabled for this application. Either enable ASP.NET
compatibility in web.config or set
thAspNetCompatibilityRequirementsAttribute.AspNetCompatibilityRequirementsMode
property to a value other than Required..
Я добавил следующий код к своему сервису:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
, но он все равно не будет работать ..
Я попытался установить aspnet_regiis.exe,но при установке обнаружена ошибка.Смотрите журнал.Но я проверил конфигурацию IIS, DefaultAPPPool и другие .NET Framework 4.0.30319.
.....2011-11-07 08:15:57 Success Getting all client file dirs and paths
2011-11-07 08:15:57 Starting Creating list of client site scripts dirs
2011-11-07 08:15:57 Starting Creating directory: C:\inetpub\wwwroot\aspnet_client
2011-11-07 08:15:57 Failure Creating directory: C:\inetpub\wwwroot\aspnet_client: CreateDirectoryInternal failed with HRESULT 80070003: 'The system cannot find the path specified. '
2011-11-07 08:15:57 Failure Creating list of client site scripts dirs: CreateSiteClientScriptDir failed with HRESULT 80070003: 'The system cannot find the path specified. '
2011-11-07 08:15:57 Failure Setting up client script files for website:*: Setting up client script files for website: failed with HRESULT 80070003: 'The system cannot find the path specified. '
2011-11-07 08:15:57 Starting Starting service: aspnet_state
2011-11-07 08:15:57 Success Starting service: aspnet_state
Журнал событий содержит следующее:
WebHost failed to process a request.
Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/62476613
Exception: System.ServiceModel.ServiceActivationException: The service '/NeuralnetworkService.svc' cannot be activated due to an exception during compilation. The exception message is: The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the service type with RequirementsMode setting as 'Allowed' or 'Required'.. ---> System.InvalidOperationException: The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the service type with RequirementsMode setting as 'Allowed' or 'Required'.
at System.ServiceModel.Activation.HostedAspNetEnvironment.ValidateCompatibilityRequirements(AspNetCompatibilityRequirementsMode compatibilityMode)
at System.ServiceModel.Activation.AspNetCompatibilityRequirementsAttribute.System.ServiceModel.Description.IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
at System.ServiceModel.Description.DispatcherBuilder.ValidateDescription(ServiceDescription description, ServiceHostBase serviceHost)
at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
at System.ServiceModel.ServiceHostBase.InitializeRuntime()
at System.ServiceModel.ServiceHostBase.OnBeginOpen()
at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
--- End of inner exception stack trace ---
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath)
Process Name: WebDev.WebServer40
Process ID: 4536
Но это нормально, чтоя не могу отправить объект через WCF?но строка из него можно отправить?
br damir
* РЕДАКТИРОВАТЬ *
Спасибо всем за помощь.Я многому научился благодаря этой проблеме и вашей помощи.Спасибо.