Размещение нескольких хостов под IIS для WCF - PullRequest
0 голосов
/ 10 сентября 2009

Мне нужно использовать несколько хостов под IIS для WCF. Мы используем wshttpbinding и до сих пор не добились успеха даже после того, как проверили пару похожих вопросов о stackoveflow.

Вот мой web.config

<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
    <configSections>
        <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                    <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
                    <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                </sectionGroup>
            </sectionGroup>
        </sectionGroup>
    </configSections>
    <appSettings/>
  <connectionStrings>
    <add name="ConString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=WebSMS20July;Integrated Security=True"/>
  </connectionStrings>
    <system.web>
    <customErrors mode="Off"/>

    <!--<httpRuntime maxRequestLength="999999999"
       useFullyQualifiedRedirectUrl="true"
       executionTimeout="459999999" appRequestQueueLimit="99999999" delayNotificationTimeout="999999999"
                  maxWaitChangeNotification="999999999" shutdownTimeout="9999999999"/>-->

    <!--
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
        <compilation debug="true">
            <assemblies>
                <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </assemblies>
        </compilation>
        <!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
        <authentication mode="Windows"/>
        <!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace. 

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>-->

        <pages>
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </controls>
        </pages>
        <httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
        </httpHandlers>
        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </httpModules>
    </system.web>
    <system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                <providerOption name="CompilerVersion" value="v3.5"/>
                <providerOption name="WarnAsError" value="false"/>
            </compiler>
        </compilers>
    </system.codedom>
 <!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules>
            <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </modules>
        <handlers>
            <remove name="WebServiceHandlerFactory-Integrated"/>
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </handlers>
    </system.webServer>
    <system.serviceModel>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"> 

      <baseAddressPrefixFilters>        
        <add prefix="http://localhost:12350"/>

      </baseAddressPrefixFilters>
    </serviceHostingEnvironment>

    <bindings>
       <wsHttpBinding>
          <binding name="wsHttpBinding" maxBufferPoolSize="2147483647"
             maxReceivedMessageSize="2147483647">
             <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
                maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
             <security mode="None">
                <transport clientCredentialType="None" />
                <message clientCredentialType="None" negotiateServiceCredential="false"
                   establishSecurityContext="false" />
             </security>
          </binding>
          <binding name="NewBinding0" />
       </wsHttpBinding>
    </bindings>
        <services>
   <service behaviorConfiguration="WcfService1.Service1Behavior"
    name="WcfService1.Service1">
    <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding"
     bindingName="wsHttpBinding" contract="WcfService1.IService1">
     <identity>
      <dns value="localhost" />
     </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <endpoint binding="wsHttpBinding" bindingConfiguration="wsHttpBinding"
     bindingName="wsHttpBinding2" contract="WcfService1.IService1"
     listenUri="http://localhost:8090" />
    <host>
     <baseAddresses>
      <add baseAddress="http://mydomain/mywcfservice/Service1.svc" />
      <add baseAddress="http://localhost/mywcfservice/Service1.svc" />
     </baseAddresses>
    </host>
   </service>
  </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="WcfService1.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>
</configuration>

Вот мой сервис фабричного класса

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace WcfService1
{
    public class CustomHostFactory : ServiceHostFactory 

    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            //CustomHost customServiceHost =
            //  new CustomHost(serviceType, baseAddresses[1]);
            //return customServiceHost;
            ServiceHost host;

            host = new ServiceHost(serviceType, baseAddresses[0]);

            return host;

        }
        class CustomHost : ServiceHost
        {
            public CustomHost(Type serviceType, params Uri[] baseAddresses)
                : base(serviceType, baseAddresses)
            { }
            protected override void ApplyConfiguration()
            {
                base.ApplyConfiguration();
            }
        }

    }
}

Содержимое моего файла Service1.svc

<%@ ServiceHost Language="C#" Debug="true" Service="WcfService1.Service1" CodeBehind="Service1.svc.cs" Factory="WcfService1.CustomHostFactory" %>

Что может быть не так?

Буду признателен за любую помощь.

Спасибо.

Ответы [ 2 ]

1 голос
/ 11 сентября 2009

Попробуйте и посмотрите, работает ли он (я действительно не уверен, что он будет работать для обоих адресов, но это возможно):

protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
    if (HttpContext.Current != null)
    {
        string baseAddress = string.Format("http://{0}{1}{2}", HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port == 80 ? "" : ":" + HttpContext.Current.Request.Url.Port, HttpContext.Current.Request.CurrentExecutionFilePath);
        Uri baseURI = new Uri(baseAddress);
        return base.CreateServiceHost(serviceType, new Uri[] { baseURI });
    }

    //We did the best we could, but there is no current HTTP request.
    //Just fall back to the base service host factory
    return base.CreateServiceHost(serviceType, baseAddresses);
}

Не похоже, что у вас включена защита транспорта, поэтому предположим, что "http://", вероятно, безопасно, но если вам нужно включить это, вам придется поработать с кодом, чтобы получить http s : // там.

0 голосов
/ 27 апреля 2010

Эй, добавь это в свой <system.serviceModel> раздел конфигурации

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

и

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class yourService : IyourService
{ ..... }

добавить using System.ServiceModel.Activation; к вашему коду

У меня тоже была такая же проблема.

...