Как запустить службу WCF при изменении пространства имен в проекте приложения службы WCF?
Я добавил тип проекта " Приложение-служба WCF " к своему решению VS (4.0). Теперь появляется пространство имен по умолчанию " Служба ", и если я запускаю приложение (указывая приложение службы WCF в качестве запускаемого проекта), оно работает нормально.
Теперь я изменил пространство имен на XXX.YYY.Service.PartnerPortal, как показано ниже.
namespace XXX.YYY.Service.PartnerPortal
{
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
}
Как и интерфейс IService1 также
namespace XXX.YYY.Service.PartnerPortal
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
}
}
Также я изменил пространство имен по умолчанию в свойствах проекта
Файл app.config находится под
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
</compilation>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
</modules>
</system.webServer>
</configuration>
И при попытке запуска появляется сообщение об ошибке:
Ошибка: невозможно получить метаданные с http://localhost:65192/Service1.svc Если это служба Windows (R) Communication Foundation, к которой у вас есть доступ, убедитесь, что вы включили публикацию метаданных по указанному адресу. Справочную информацию о включении публикации метаданных см. В документации MSDN по адресу http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata URI ошибки обмена: http://localhost:65192/Service1.svc Metadata содержит ссылка, которая не может быть разрешена: 'http://localhost:65192/Service1.svc'. Сервер не дал значимого ответа; Это может быть вызвано несоответствием контракта, преждевременным завершением сеанса или внутренней ошибкой сервера.HETTP GET Ошибка URI: http://localhost:65192/Service1.svc Произошла ошибка при загрузке 'http: // localhost: 65192 / Service1.svc. Запрос не выполнен с сообщением об ошибке: - Не удалось найти тип "Service.Service1", предоставленный в качестве значения атрибута Service в директиве ServiceHost или в элементе конфигурации system.serviceModel/serviceHostingEnvironment/serviceActivations. body {font-family: "Verdana"; font-weight: normal; font-size:.7em; цвет: черный;} p {font-family:"Verdana";font-weight:normal; цвет: черный;margin-top: -5px} b {font-family:"Verdana";font-weight:bold; цвет: черный;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font- размер:18pt; цвет: красный} H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Lucida Console"; размер шрифта: .9em} .marker {font-weight: bold; цвет: черный; текстовое оформление: нет;} .version {цвет: серый;} .error {margin-bottom: 10px;} .expandable {текстовое оформление: подчеркивание; начертание шрифта: жирный; Цвет: темно - синий; Курсор: рука; }
Ошибка сервера в приложении '/'
Тип 'Service.Service1', предоставленный в качестве значения атрибута Service в директиве ServiceHost или предоставленный в элементе конфигурации system.serviceModel/serviceHostingEnvironment/serviceActivations, не найден.
Описание: во время выполнения текущего веб-запроса произошло необработанное исключение. Пожалуйста, просмотрите трассировку стека для получения дополнительной информации об ошибке и о том, где она возникла в коде.Сведения об исключении: System.InvalidOperationException: Не удалось найти тип "Service.Service1", предоставленный в качестве значения атрибута Service в директиве ServiceHost или в элементе конфигурации system.serviceModel/serviceHostingEnvironment/serviceActivations.
Ошибка источника:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Трассировки стека:
[InvalidOperationException: The type 'Service.Service1', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.] System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +51530 System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +1461 System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +44 System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +651[ServiceActivationException: The service '/Service1.svc' cannot be activated due to an exception during compilation. The exception message is: The type 'Service.Service1', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found..] System.Runtime.AsyncResult.End(IAsyncResult result) +688590 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +190 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, String routeServiceVirtualPath, Boolean flowContext, Boolean ensureWFService) +234 System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +359 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +148 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Информация о версии: icroMicrosoft .NET Framework Версия:4.0.30319; ASP.NET версия:4.0.30319.272 -.
Что не так делаю и как это исправить?
2 ответа
Откройте файл SVC и исправьте пространство имен в значении атрибута Service.
<%@ ServiceHost Language="C#" Debug="true" Service="XXX.YYY.Service.PartnerPortal.Service1" .....
Изменен файл конфигурации как под
<system.serviceModel>
<services>
<service behaviorConfiguration="Service.Service1Behavior" name="XXX.YYY.Service.PartnerPortal.Service1">
<endpoint address="" binding="wsHttpBinding" contract="XXX.YYY.Service.PartnerPortal.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Service.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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>
</behaviors>
</system.serviceModel>