2015-01-20 2 views
4

Я пытаюсь разместить службу WCF net.pipe в службе Windows. Я определяю службу в коде, в функции OnStart() службы Windows. Я также создаю клиента аналогичным образом - в коде.Запрошенное обновление не поддерживается «net.pipe: //»

Я видел этот вопрос, но он всегда кажется, что он посвящен только ситуациям, когда NetNamedPipe определен в файле app/web.config.

При попытке вызова службы, я получаю ошибку:

System.ServiceModel.ProtocolException: The requested upgrade is not supported by 'net.pipe://localhost/manager'. This could be due to mismatched bindings (for example security enabled on the client and not on the server). 

Server stack trace: 
    at System.ServiceModel.Channels.ConnectionUpgradeHelper.DecodeFramingFault(ClientFramingDecoder decoder, IConnection connection, Uri via, String contentType, TimeoutHelper& timeoutHelper) 
    at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper) 
    at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper) 
    at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout) 
    at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout) 
    at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) 
    at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout) 
    at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) 
    at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade) 
    at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout) 
    at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) 
    at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) 
    at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) 

Exception rethrown at [0]: 
    at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) 
    at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) 
    at MyClientApp.IManager.HelloWorld() 

Вот мой код:

//Service Contract: 
[ServiceContract] 
public interface IManager 
{ 
    [OperationContract] 
    string HelloWorld(); 
} 

//Service 
public class Manager : IManager 
{ 
    public string HelloWorld() 
    { 
     return "Hello to you too!"; 
    } 
} 

//Defining and starting the Net.Pipe Service from the Windows Service 
public partial class MyWindowsService : ServiceBase 
{ 
    public MyWindowsService() 
    { 
     InitializeComponent(); 
    } 

    private ServiceHost m_serviceHost; 
    protected override void OnStart(string[] args) 
    { 
     try 
     { 
      m_serviceHost = new ServiceHost(typeof(Manager), new Uri("net.pipe://localhost")); 
      NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); 
      m_serviceHost.AddServiceEndpoint(typeof(IManager), binding, "manager"); 
      m_serviceHost.Open(); 
     } 
     catch (Exception ex) 
     { 
      EventLog("MyWindowsService", ex.ToString(), EventLogEntryType.Error); 
     } 
    } 
} 

//The client proxy 
public class ManagerProxy : ClientBase<IManager> 
{ 
    public ManagerProxy() 
     : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IManager)), 
      new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/manager"))) { } 

    public string InvokeHellowWorld() 
    { 
     return Channel.HelloWorld(); 
    } 
} 

Интерфейс находится в ClassLibrary проекта и распределяется между хост-приложением (служба Windows) и клиентское приложение, которое пытается вызвать службу.

Класс обслуживания и функция OnStart находятся в проекте службы Windows.

Прокси-сервер службы находится в клиентском проекте (который, конечно же, запускается с того же компьютера, что и служба Windows).

Кроме того, всякий раз, когда я пытаюсь использовать прокси-сервер, я нахожу его State == CommunicationState.Faulted. Затем я закрываю/прерываю его и создаю new ManagerProxy(). Состояние ManagerProxy составляет Created. Я пытаюсь вызвать HelloWorld и получить выше Exception.
В следующий раз, когда я попытаюсь его использовать, его состояние снова появляется Faulted, и процесс повторяется.

ответ

12

Единственное отличие, которое я вижу, это то, что на стороне сервера вы создаете привязку с явно отсутствующим режимом безопасности binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); и на стороне клиента без режима безопасности new NetNamedPipeBinding(). Сообщение об исключении указывает на то, что безопасность является потенциальным несоответствием.

System.ServiceModel.ProtocolException: The requested upgrade is not supported by 'net.pipe://localhost/manager'. This could be due to mismatched bindings (for example security enabled on the client and not on the server).

Только что проверил here и режим безопасности по умолчанию не NetNamedPipeSecurityMode.None это NetNamedPipeSecurityMode.Transport. Таким образом, существует несоответствие.

1

, если ни один из вышеперечисленных работ решения для вас, то попробуйте удалить идентификатор из вашей конечной точки, как не показаны ниже:

<endpoint address="net.tcp://127.0.0.1/FacilitySchedulesService/FacilitySchedulesService.svc" 
       binding="netTcpBinding" bindingConfiguration="FacilityScheduleDSTCP" 
       contract="FacilitySchedules.IFacilitySchedulesService" name="FacilityScheduleDSTCP"> 
     <!--<identity> 
      <userPrincipalName value="abc" /> 
     </identity>--> 
     </endpoint> 
Смежные вопросы