2016-06-10 9 views
0

ОБНОВЛЕНИЕ Следующие проблемы могут быть вызваны тем, что net.tcp не используется в IIS express. Хорошие ответы (желательно примеры) по-прежнему очень приветствуются.Host WCF-служба, использующая привязку и настройку NetTcp в коде, размещенном в IIS

Я пытаюсь разместить службу WCF в IIS без использования файла web.config (msdn documentation on the basics on that). Я хочу использовать сеансы и NetTcpBinding, но у меня, похоже, возникают проблемы с работой метаданных. Я пробовал немало вещей. Вот мой текущий код:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] 
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
public class InternalInternalESensService : IInternalESensService 
{ 
    public static void Configure(System.ServiceModel.ServiceConfiguration config) 
    { 
     NetTcpBinding wsBind = new NetTcpBinding(SecurityMode.Transport); 
     config.AddServiceEndpoint(typeof(IInternalESensService), wsBind, "net.tcp://localhost:42893/ESens/ESensInternalService.svc"); 
     // config.AddServiceEndpoint(typeof(IInternalESensService), basic, "basic"); 
     // config.Description.Endpoints.Add(new ServiceMetadataEndpoint(MetadataExchangeBindings.CreateMexHttpBinding(), new EndpointAddress(config.BaseAddresses[0]))); 
     config.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetBinding = MetadataExchangeBindings.CreateMexHttpBinding()}); 
     //config.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); 
     config.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); 
    } 

    public string Test(string input) 
    { 
     return "Hello " + input; 
    } 

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

[ServiceContract(Name = "ESensInternalService", Namespace = Constants.WebserviceNameSpace + "/ESensService", SessionMode = SessionMode.Required)] 
public interface IInternalESensService 
{ 
    [OperationContract] 
    string Test(string input); 

Есть еще несколько методов в реализации интерфейса и класса, но они не имеют отношения к вопросу/проблеме.

Чтобы разместить его в IIS, я использую файл svc. Содержимое выглядит примерно так:

<%@ ServiceHost Language="C#" Debug="true" Service="Esens.Integration.WebService.InternalInternalESensService" %> 

У меня есть много разных исключений, в зависимости от того, что я сделал.

ответ

0

Я сам нашел ответ. Прежде всего I found that you cannot use net.tcp binding in IIS express. Также он должен быть (нормальный) enabled on the IIS.

Тогда он может быть сконфигурирован следующим образом:

public static void Configure(System.ServiceModel.ServiceConfiguration config) 
    { 
     Uri netTcpAddress = config.BaseAddresses.FirstOrDefault(x => x.Scheme == Uri.UriSchemeNetTcp); 
     if (netTcpAddress == null) 
     { 
      throw new InvalidOperationException("No base address matches the endpoint binding net.tcp"); 
     } 

     Uri metaAddress = config.BaseAddresses.FirstOrDefault(x => x.Scheme == Uri.UriSchemeHttp); 
     if (metaAddress == null) 
     { 
      throw new InvalidOperationException("No base address matches the endpoint binding http used for metadata"); 
     } 

     config.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true }); 

     NetTcpBinding wsBind = new NetTcpBinding(SecurityMode.Transport); 
     ServiceEndpoint endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IInternalESensService)), wsBind, new EndpointAddress(netTcpAddress)); 
     config.AddServiceEndpoint(endpoint); 

     Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding(); 
     ContractDescription contractDescription = ContractDescription.GetContract(typeof(IMetadataExchange)); 
     contractDescription.Behaviors.Add(new ServiceMetadataContractBehavior(true)); 
     ServiceEndpoint mexEndpoint = new ServiceEndpoint(contractDescription, mexBinding, new EndpointAddress(metaAddress)); 
     mexEndpoint.Name = "mexTest"; 
     config.AddServiceEndpoint(mexEndpoint); 

     config.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); 
    } 

Кажется, там не так много документации по этому вопросу. Мне пришлось посмотреть на некоторые из исходных кодов Microsoft, чтобы найти специальную часть о поведении привязок метаданных.

Если вы хотите сделать то же самое в web.config это будет выглядеть примерно так:

<service behaviorConfiguration="StandardBehaviour" name="Mercell.Esens.Integration.WebService.InternalInternalESensService"> 
    <endpoint binding="netTcpBinding" 
    name="test" contract="Mercell.Esens.Integration.WebService.IInternalESensService" /> 
    <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="" 
    name="Metadata" contract="IMetadataExchange" /> 
    </service> 

С поведением:

<behavior name="StandardBehaviour"> 
<serviceMetadata httpGetEnabled="true" /> 
</behavior> 

 Смежные вопросы

  • Нет связанных вопросов^_^