---
title: "[原创] WCF技术剖析之六：为什么在基于ASP.NET应用寄宿（Hosting）下配置的BaseAddress无效"
author: "varsoft"
date: "2009-06-26T19:10:00Z"
tags: []
slug: "wcf-asp-net-hosting-baseaddress"
draft: false
lastmod: "2009-06-26T19:10:00Z"
id: 871306
url: "https://varsoft.iteye.com/blog/871306"
---

本篇文章来源于几天前一个朋友向我咨询的问题。问题是这样的，他说他采用ASP.NET应用程序的方式对定义的WCF服务进行寄宿（Hosting），并使用配置的方式对服务的BaseAddress进行了设置，但是在创建ServiceHost的时候却抛出InvalidOperationException，并提示相应Address Scheme的BaseAddress找不到。我意识到这可能和WCF中用于判断服务寄宿方式的逻辑有关，于是我让这位朋友将相同的服务寄宿代码和配置迁移到GUI程序或者Console应用中，看看是否正常。结果如我所想，一切正常，个人觉得这应该是WCF的一个Bug。今天撰文与大家讨论，看看大家对这个问题有何见解。

**一、问题重现**

问题很容易重现，假设我们通过ASP.NET应用对服务CalculatorService进行寄宿，为了简单起见，我将服务契约和服务实现定义在一起。CalculatorService的定义如下面的代码片断所示：

&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /\*white-space: pre;\*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } &lt;/style&gt;

```
   1: using System.ServiceModel;
```

&lt;!--CRLF--&gt;

```
   2: namespace Artech.AspnetHostingDemo
```

&lt;!--CRLF--&gt;

```
   3: {
```

&lt;!--CRLF--&gt;

```
   4:     [ServiceContract(Namespace = "urn:artech.com")]
```

&lt;!--CRLF--&gt;

```
   5:     public class CalculatorService
```

&lt;!--CRLF--&gt;

```
   6:     {
```

&lt;!--CRLF--&gt;

```
   7:         [OperationContract]
```

&lt;!--CRLF--&gt;

```
   8:         public double Add(double x, double y) { return x + y; }
```

&lt;!--CRLF--&gt;

```
   9:     }
```

&lt;!--CRLF--&gt;

```
  10: }
```

&lt;!--CRLF--&gt;

下面是服务寄宿相关的配置，在&lt;host&gt;/&lt;baseAddresses&gt;配置节中为服务添加了一个Scheme为http的BaseAddress：[http://127.0.0.1:3721/services](http://127.0.0.1:3721/services)，那么终结点的地址就可以定义为基于该BaseAddress的相对地址了：calculatorservice。

```
   1: <?xml version="1.0"?>
```

&lt;!--CRLF--&gt;

```
   2: <configuration>
```

&lt;!--CRLF--&gt;

```
   3:   <system.serviceModel>
```

&lt;!--CRLF--&gt;

```
   4:     <services>
```

&lt;!--CRLF--&gt;

```
   5:       <service name="Artech.AspnetHostingDemo.CalculatorService">
```

&lt;!--CRLF--&gt;

```
   6:         <host>
```

&lt;!--CRLF--&gt;

```
   7:           <baseAddresses>
```

&lt;!--CRLF--&gt;

```
   8:             <add baseAddress="http://127.0.0.1:3721/services"/>
```

&lt;!--CRLF--&gt;

```
   9:           </baseAddresses>
```

&lt;!--CRLF--&gt;

```
  10:         </host>
```

&lt;!--CRLF--&gt;

```
  11:         <endpoint address="calculatorservice" binding="wsHttpBinding" contract="Artech.AspnetHostingDemo.CalculatorService"/>
```

&lt;!--CRLF--&gt;

```
  12:       </service>
```

&lt;!--CRLF--&gt;

```
  13:     </services>
```

&lt;!--CRLF--&gt;

```
  14:   </system.serviceModel>
```

&lt;!--CRLF--&gt;

```
  15:   <system.web>
```

&lt;!--CRLF--&gt;

```
  16:     <compilation debug="true"/>
```

&lt;!--CRLF--&gt;

```
  17:   </system.web>
```

&lt;!--CRLF--&gt;

```
  18: </configuration>
```

&lt;!--CRLF--&gt;

我们把服务寄宿的代码定义在一个Web Page的Load事件中。但程序执行到到创建ServiceHost的时候，抛出如下图所示的InvalidOperationException异常。

[](http://images.cnblogs.com/cnblogs_com/artech/WindowsLiveWriter/WCFASP.NETHostingBaseAddress_1092C/image_2.png)

[![image](http://images.cnblogs.com/cnblogs_com/artech/WindowsLiveWriter/WCFASP.NETHostingBaseAddress_1092C/image_thumb.png "image")](http://images.cnblogs.com/cnblogs_com/artech/WindowsLiveWriter/WCFASP.NETHostingBaseAddress_1092C/image_2.png)

下面是错误信息和异常的StackTrace:

&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /\*white-space: pre;\*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } &lt;/style&gt;

```
   1: Could not find a base address that matches scheme http for the endpoint with binding WSHttpBinding. Registered base address schemes are [].
```

&lt;!--CRLF--&gt;

```
   1: at System.ServiceModel.ServiceHostBase.MakeAbsoluteUri(Uri relativeOrAbsoluteUri, Binding binding, UriSchemeKeyedCollection baseAddresses)   
```

&lt;!--CRLF--&gt;

```
   2: at System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress)   
```

&lt;!--CRLF--&gt;

```
   3: at System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection)   
```

&lt;!--CRLF--&gt;

```
   4: at System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, String configurationName)   
```

&lt;!--CRLF--&gt;

```
   5: at System.ServiceModel.ServiceHostBase.ApplyConfiguration()   
```

&lt;!--CRLF--&gt;

```
   6: at System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses)   
```

&lt;!--CRLF--&gt;

```
   7: at System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses)   
```

&lt;!--CRLF--&gt;

```
   8: at System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses)   
```

&lt;!--CRLF--&gt;

```
   9: at Artech.AspnetHostingDemo._Default.Page_Load(Object sender, EventArgs e) in e:\WCF Projects\AspnetHostingDemo\AspnetHostingDemo\Default.aspx.cs:line 16   
```

&lt;!--CRLF--&gt;

```
  10: at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)   
```

&lt;!--CRLF--&gt;

```
  11: at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)   
```

&lt;!--CRLF--&gt;

```
  12: at System.Web.UI.Control.OnLoad(EventArgs e)   at System.Web.UI.Control.LoadRecursive()   
```

&lt;!--CRLF--&gt;

```
  13: at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
```

&lt;!--CRLF--&gt;

**二、问题分析**

通过上面提供StackTrace，我们可以看到错误发生在WCF试图将BaseAddress和RelativeAddress进行组合生成AbsoluteAddress的时候。从错误消息可以看出，在进行地址的组合时，由于没有找到适合绑定类型（WsHttpBinding）Scheme（http）的BaseAddress，导致了异常的抛出。

要解答这个问题，首先要解释一下WCF的BaseAddress在不同服务寄宿（Service Hosting）方式下的定义方式。对于WCF服务的自我寄宿（Self Hosting）或者采用Windows Service进行服务寄宿，我们可以通过代码或者形如上面的配置为服务指定一系列的BaseAddress（对于一个既定的URI Scheme，只能由唯一的BaseAddress）。但是对于采用IIS或者WAS进行服务寄宿，我们需要为相应的服务定义一个.svc文件，我们通过访问.svc文件的方式来调用相应的服务。对于后者，.svc文件得地址就是WCF服务的BaseAddress，所以WCF会忽略BaseAddress的配置。

那么WCF采用怎样的方式来判断当前服务寄宿的方式是基于IIS呢，还是其他呢？答案是通过System.Web.Hosting.HostingEnvironment的静态属性IsHosted。对于ASP.NET有一定了解的人应该很清楚，在一个ASP.NET应用下，该属性永远返回为True。也就是说，WCF会把基于ASP.NET应用的服务寄宿，看成是基于IIS的服务寄宿，这显然是不对的。

```
   1: public sealed class HostingEnvironment : MarshalByRefObject
```

&lt;!--CRLF--&gt;

```
   2: {     //其他成员
```

&lt;!--CRLF--&gt;

```
   3:     public static bool IsHosted { get; }
```

&lt;!--CRLF--&gt;

```
   4: }
```

&lt;!--CRLF--&gt;

WCF对BaseAddress配置的加载和添加的逻辑定义在ServiceHostBase的LoadHostConfig方法中，大致的逻辑如下面的代码所示：

&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /\*white-space: pre;\*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } &lt;/style&gt;

```
   1: public abstract class ServiceHostBase : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
```

&lt;!--CRLF--&gt;

```
   2: {
```

&lt;!--CRLF--&gt;

```
   3:     [SecurityTreatAsSafe, SecurityCritical]
```

&lt;!--CRLF--&gt;

```
   4:     private void LoadHostConfig(ServiceElement serviceElement, ServiceHostBase host, Action<Uri> addBaseAddress)
```

&lt;!--CRLF--&gt;

```
   5:     {
```

&lt;!--CRLF--&gt;

```
   6:         HostElement element = serviceElement.Host; if (element != null)
```

&lt;!--CRLF--&gt;

```
   7:         {
```

&lt;!--CRLF--&gt;

```
   8:             if (!ServiceHostingEnvironment.IsHosted)
```

&lt;!--CRLF--&gt;

```
   9:             {                //BaseAddress配置加载与添加
```

&lt;!--CRLF--&gt;

```
  10:             }
```

&lt;!--CRLF--&gt;

```
  11:         }
```

&lt;!--CRLF--&gt;

```
  12:     }
```

&lt;!--CRLF--&gt;

```
  13: }
```

&lt;!--CRLF--&gt;

```
   1: public static class ServiceHostingEnvironment
```

&lt;!--CRLF--&gt;

```
   2: {
```

&lt;!--CRLF--&gt;

```
   3:     private static bool isHosted; internal static bool IsHosted { get { return isHosted; } }
```

&lt;!--CRLF--&gt;

```
   4:     internal static void EnsureInitialized()
```

&lt;!--CRLF--&gt;

```
   5:     {
```

&lt;!--CRLF--&gt;

```
   6:         if (hostingManager == null)
```

&lt;!--CRLF--&gt;

```
   7:         {
```

&lt;!--CRLF--&gt;

```
   8:             lock (ThisLock)
```

&lt;!--CRLF--&gt;

```
   9:             {
```

&lt;!--CRLF--&gt;

```
  10:                 if (hostingManager == null)
```

&lt;!--CRLF--&gt;

```
  11:                 {
```

&lt;!--CRLF--&gt;

```
  12:                     if (!HostingEnvironmentWrapper.IsHosted)
```

&lt;!--CRLF--&gt;

```
  13:                     {
```

&lt;!--CRLF--&gt;

```
  14:                         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("Hosting_ProcessNotExecutingUnderHostedContext", new object[] { "ServiceHostingEnvironment.EnsureServiceAvailable" })));
```

&lt;!--CRLF--&gt;

```
  15:                     }
```

&lt;!--CRLF--&gt;

```
  16:                     HostingManager manager = new HostingManager();
```

&lt;!--CRLF--&gt;

```
  17:                     HookADUnhandledExceptionEvent(); 
```

&lt;!--CRLF--&gt;

```
  18:                     Thread.MemoryBarrier(); 
```

&lt;!--CRLF--&gt;

```
  19:                     isSimpleApplicationHost = GetIsSimpleApplicationHost();
```

&lt;!--CRLF--&gt;

```
  20:                     hostingManager = manager; 
```

&lt;!--CRLF--&gt;

```
  21:                     isHosted = true;
```

&lt;!--CRLF--&gt;

```
  22:                 }
```

&lt;!--CRLF--&gt;

```
  23:             }
```

&lt;!--CRLF--&gt;

```
  24:         }
```

&lt;!--CRLF--&gt;

```
  25:     }
```

&lt;!--CRLF--&gt;

```
  26: }
```

&lt;!--CRLF--&gt;

```
  27: 
```

&lt;!--CRLF--&gt;

```
   1: internal static class HostingEnvironmentWrapper
```

&lt;!--CRLF--&gt;

```
   2: {
```

&lt;!--CRLF--&gt;

```
   3:     public static bool IsHosted
```

&lt;!--CRLF--&gt;

```
   4:     {
```

&lt;!--CRLF--&gt;

```
   5:         get { return HostingEnvironment.IsHosted; }
```

&lt;!--CRLF--&gt;

```
   6:     }
```

&lt;!--CRLF--&gt;