Friday, November 28, 2008

What is IIS7?

What is IIS7? What is the difference between IIS6 and IIS7? Here are the simple answers:

§ IIS7 is a new revision (version 7.0) of the Internet Information Services that is shipped on Windows Vista and the next Windows Server version.

§ The most attractive features of IIS7 are: modular design (thanks to the new Windows componentization technology first introduced in Windows Vista), extensible architecture (with public web server APIs), and unified distributed configuration system.

§ Another big change to IIS7 is that it first introduced a new NT service “Windows Process Activation Service” (WAS). WAS manages application pool configuration and worker processes. This enables process activation through both HTTP and non-HTTP transports.

More details about IIS7 can be found in the IIS7 public web site:http://www.iis.net/.

When people asked me how to host WCF services on IIS7? I would always say: it is the same as on IIS6. Well, this is generally correct. People still kept on hitting unique problems on IIS7. I will expand this in more details in my future blog entries.

Virtual Application vs Virtual Directory

People are always confused by these two IIS concepts, especially for the new IIS7/WAS. These are not new concepts. They are available since IIS6 on Windows 2003 Server. However the terms were misused in IIS6 and they are corrected in IIS7 in Windows Vista and higher versions of Windows.

Virtual Application

What is it?

The term “virtual application” is a fundamental concept for IIS and ASP.NET. Here is the definition in my own words: a virtual application is a construction unit of a web site that participates protocol listening and process management. It can be uniquely identified by its absolute virtual path from that web site. For example, you can create a virtual application with virtual path “/foo” in the “Default Web Site”. For simplicity, we also call virtual application as "Default Web Site/foo" or simply “/foo”. Every web site has at least one virtual application, a.k.a, the root virtual application “/”.

A web site can be uniquely identified by its site ID. All of the web sites are under the same root “/W3SVC”. So each web site can be represented in the format of “/W3SVC/”. For example, the “Default Web Site” can be represented as “/W3SVC/1”. With this, we can uniquely identify a virtual application with its full path, for example,

/W3SVC/1/Root/foo

If you have the IIS6 scripting tool “adsutil.vbs” installed, you would be able to check the settings of the virtual application with the following command:

cscript %systemdrive%\inetpub\adminscripts\adsutil.vbs enum /W3SVC/1/Root/foo

Protocol Listening

When you create a virtual application, you would expect your new virtual application to receive requests that are dedicated to it. There are two aspects of “protocol listening”:

  • For a particular protocol (for example HTTP), a web site is nothing but a list of virtual applications. This means that the protocol activation service (which is IIS or W3SVC in the HTTP case) registers a list of Urls in the protocol listener service (which is HTTP.sys driver for HTTP). Each of this Url is associated with a virtual application.
  • You can specify which protocol is enabled for a virtual application. In IIS6, you can specify HTTP or HTTPS. In IIS7, however, you can specify any protocol(s) through the “enabledProtocols” property of the virtual application. For example, you can specify protocols “net.tcp”, “net.pipe”, “net.msmq”, or “msmq.formatname” that are implemented by WCF.
Application Pool

The other aspect of a virtual application is that it also participates in process management. IIS/WAS has the concept of application pools. An application pool is a definition or template of a worker process (w3wp.exe) that is used by IIS/WAS to create new worker process instances. Two most important properties of an application pool are:

Each virtual application must be assigned to an application pool in IIS. All of the requests (except for static content) will be handled in worker processes in that application pool.

Please note that Application Pool is managed by WAS instead of IIS in the IIS7 family. This separation makes non-HTTP activation possible. With this refactoring, “IIS” is simply the web server that only handles HTTP/HTTPS requests.

ASP.NET Application

For ASP.NET, a virtual application has its real meaning as an “application”. When an ASP.NET request is first received in a virtual application, a new AppDomain is created in the worker process that handles subsequent ASP.NET requests. This includes all WCF requests. So in the ASP.NET world, a virtual application is mapped to an AppDomain. This provides important code isolation for managed applications that sits in the same worker process. It is even more important for web hosting when the applications are running in the partial trust environment.

Virtual Directory

Isn’t “virtual directory” the same as “virtual application”? In IIS6, from the IIS Manager (UI), if you right click on “Default Web Site” -> New, you will see “Virtual Directory …” from the list. What is going on there? Well, as I said, the terms are misused in IIS6. When it says “Virtual Directory”, it actually means “Virtual Application”.

Am I kidding? No. A real “virtual directory” is just a container of files. It is a construction unit of a virtual application, just like a virtual application to a web site. A virtual application must have at least one virtual directory. Here is a sample configuration section that defines the virtual application “/foo” and its virtual directories in the WAS' configuration file %windir%\system32\inetsrv\config\applicationhost.config:

<sites>

<site name="Default Web Site" id="1">

<application path="/foo" enabledProtocols="http">

<virtualDirectory path="/"physicalPath="c:\inetpub\foo" />

<virtualDirectory path="/bar"physicalPath="\\myremote1\bar" />

application>

...

site>

sites>

Note that the virtual directory “/bar” points to a different physical path, actually it points to a network share (UNC) path!

How can we create a real virtual directory in IIS6 then? It is a little bit trickier from the UI. In the IIS Manager UI, you can right click on the virtual application and then click on New -> “Virtual Directory …”. After specifying the alias and path, you will get the virtual directory using all default settings.

However, there is another trick to convert a virtual application into a virtual directory. Here are the steps:

  • Create a virtual application “/foo” and a sub virtual application “/foo/bar”.
  • Right click on the virtual application “/foo/bar” and select properties. You will see the properties dialog popped up.
  • Under the “Virtual Directory” tab, look for the “Remove” button. See the image below:

  • Click the “Remove” button and click on “OK” button.

Now you have created a virtual directory “/bar” under the virtual application “/foo”. The icon for the virtual application is different than that of the virtual application. Here is what you will see:

Nesting

Virtual applications and virtual directories can be nested, meaning, a virtual application or directory can be created under another virtual application or directory in any combinations.

This nesting has the following implications:

  • The virtual path of the parent application/directory is the prefix of the child application/directory.
  • For ASP.NET, the web.config of the parent virtual application/directory affects the child application/directory.
  • For ASP.NET, the assemblies referenced by the parent virtual application are inherited by the children.
Other than those, virtual applications still have their own isolation that I mentioned in the above sections.

IIS7/WAS Installation

IIS7 has a modular design which allows you to selectively install components that are needed. This design is based on the new manifest-driven Componentization technology that was first introduced in Windows Vista. As the IIS site claimed, there are more than 40 standalone feature components of IIS7 which can be independently installed. This is good or bad. The good part is that IT professionals can easily customize the installation as needed. The bad part is that it’s hard for developers to understand which components are needed. Here I would like to write something regarding the latter.

If you are familiar with CMI (Component Management Interface) or CBS (Component Based Setup), you would know that there are many different ways to install components on Vista. You can use the GUI interface (called Software Explorer) which is available from “Control Panel” -> Programs -> “Turn Windows features on or off”. Or you can use command-line tools such as pkgmgr.exe or ocsetup.exe (which is a wrapper of pkgmgr.exe). I will talk about the simplest approach, GUI interface, below.

Minimal Installation: Installing WAS

The minimal installation of the whole IIS7 package is to install the Windows Process Activation Service (WAS). WAS is a standalone feature and it is the only feature from the IIS7 family that is available for all Windows Vista client SKUs (Basic, Home, Business, and Ultimate, etc).

From the “Turn Windows features on or off” UI of the control panel, you will see the WAS component listed in the list as in the following image:

This feature has three sub-components:

  • .NET Environment
  • Configuration APIs
  • Process Model

If you select the root node of WAS, only the “Process Model” sub-node is checked to be installed by default with the root. Please note that with this installation, you still cannot do anything interesting today. It only means that you can get WAS to work.

If you further check the “Internet Information Services” feature from the feature list, you will find out that the “Configuration APIs’ node is automatically checked.

In order to make WCF or any ASP.NET application to work, you need to further check the sub-node “.NET Environment”. This means that all of WAS components are needed in order to make WCF/ASP.NET to work well. Fortunately these are automatically checked once you install any of those components.

IIS7: Default Installation

By simply checking the “Internet Information Services” feature from the UI, you will see that quite some sub-nodes are automatically marked as following:

This is the default installation of IIS7. In this way, you can use IIS7 to service static content (such as HTML pages etc). However, you can’t run ASP.NET or CGI applications.

IIS7: Installlation with ASP.NET support

From the above image, it’s obvious that you need to install “ASP.NET” to make ASP.NET work on IIS7. After checking “ASP.NET”, you will find the following UI:

This is the minimal environment for both WCF and ASP.NET applications to work in IIS7.

Installation with IIS6 Compatibility Components

Many people still have problems with the above installation when they run Visual Studio 2005 or some automation scripts/tools (for example, adsutil.vbs) to configure virtual applications. The main reason is because those tools depend on the legacy IIS6 Metabase API support as well as the legacy IIS6 scripting tools. Here is the UI that shows what are missing from above:

You need to check “IIS 6 Scripting Tools” (which automatically checks other three subnodes of “IIS 6 Management Compatibility”). After that, you will see the following UI:

With this installation, you are good to play with IIS7, ASP.NET, and WCF features and samples available on the web.

Maximum Installation

You may want to play with other components that are not installed by default. To install them, you can simply go through the whole tree of the IIS and check every leaf node. In this way, you will get the full IIS7 feature set installed.

Impersonation with Double Identities

There are two different levels of security that you can use for WCF services: Message level and Transport level. For Transport level, in HTTP case, you can use different IIS Authentication mechanisms to perform client authentication. If you do not carefully set the settings of the WCF binding, you may end up with both security levels enabled. This has a direct impact of impersonation. The reason is because WCF does not know which identity you want to apply to impersonation.

Generally, it is not recommended to have double securities enabled. However, there is actually a reason why people could get into this dilemma:

  • It is normal for people to disable anonymous access in IIS. In WCF, we want to make sure that a service explicitly specifies its transport level security settings. In this case, it means that you have to configure the service to not use anonymous authentication at transport layer. So when you also want to enable message-level security to perform message signing or encryption, you would get into this double-identity situation.

Here is a simple custom binding configuration that demonstrates how it is the case of double identities:

<customBinding>

<binding name="mixedSecureBinding">

<security/>

<httpTransport authenticationScheme="Ntlm"/>

binding>

customBinding>

It enables both message-level security and it also enables the NTLM authentication at the transport layer.

In this case, if you have an operation which requires impersonation, you would get the following error on the server side (you can see it from a debugger):

System.InvalidOperationException: Cannot start impersonation because the SecurityContext for the UltimateReceiver role from the request message with the 'http://www.microsoft.com/test/IHelloContract/Hello' action is not mapped to a Windows identity.

This is because WCF actually set the ServiceSecurityContext to WindowsIdentity.Anonymous when multiple identifies are found.

There are three different ways to resolve this issue.

1. Enable Anonymous Access from IIS

This is the simplest way, though there is a security concern for this approach. Here is the binding configuration that does not have the transport-layer authentication enabled:

<customBinding>

<binding name="mixedSecureBinding">

<security/>

<httpTransport/>

binding>

customBinding>

You have to enable the anonymous access in IIS to make this work, otherwise you would get ServiceActivationException on the server side due to mismatched settings between WCF binding and IIS.

This is not the ideal solution if you have other services in the same application that you want to have anonymous access disabled for security purpose.

2. Use Imperative Impersonation

When I said impersonation would fail above, I meant declarative (or automatic) impersonation. Here is the sample service operation that does this:

[OperationBehavior(Impersonation =ImpersonationOption.Required)]

public string Hello(string greeting)

To use imperative impersonation, you need to remove the “Impersonation” setting from the above declaration and perform impersonation from code. This requires having a Windows identity being retrieved from the context. Fortunately WCF provides a way for you to find the identities that are available in the stack:

OperationContext.Current.ServiceSecurityContext.AuthorizationContext.Properties["Identities"]

You can cast this into List and examine each identity of them. You cannot tell which identity is from which layer though. However, in WCF V1, the identity from the transport layer is always the first one. But this is guaranteed in future versions.

Once you have the Windows identity, you can perform the impersonation by yourself:

using (identity.Impersonate())

{

// Do something

}

3. Remove Unnecessary Identities Using Custom Authorization Policy

If you are still not satisfied by the above approaches, here is another choice for you. You need to use the ServiceAuthorizationBehavior.ExternalAuthorizationPolicies extension point to add an extra authorization policy to remove identities which are not needed. Here is a good sample about how to implement a custom authorization policy: http://msdn2.microsoft.com/en-gb/library/aa702720.aspx.

In our case, we can implement the Evaluate() method of the custom MyAuthorizationPolicy as following so that the last identity is picked:

public bool Evaluate(EvaluationContext evaluationContext, refobject state)

{

IList<IIdentity> identities = evaluationContext.Properties["Identities"] as IList<IIdentity>;

if (identities != null && identities.Count > 1)

{

// Pick the last one (which is likely to be the identity embeded in the message.

evaluationContext.Properties["Identities"] =

new List<IIdentity>(new IIdentity[] { identities[identities.Count - 1] });

}

return true;

}

Now you can configure the Authorization behavior in your ServiceHost. You need to implement ServiceHostFactory so that this custom behavior can be added to the ServiceHost. Here is an implementation of the CreateServiceHost method:

public override ServiceHostBase CreateServiceHost(stringconstructorString, Uri[] baseAddresses)

{

ServiceHost serviceHost = newServiceHost(typeof(HelloService), baseAddresses);

serviceHost.Authorization.ExternalAuthorizationPolicies =new ReadOnlyCollection<IAuthorizationPolicy>(

new IAuthorizationPolicy[] {

new MyAuthorizationPolicy()

});

return serviceHost;

}

The sample code for this blog entry is attached.

How to change HostName in WSDL for an IIS-hosted service?

If you have a web-hosted service “simple.svc” under the virtual application “/simple”, you would probably get the following service address in the WSDL:

<wsdl:service name="SimpleService">

<wsdl:port name="BasicHttpBinding_ISimpleContract"binding="tns:BasicHttpBinding_ISimpleContract">

<soap:address location="http://mycomputer.private.mydomain.com/simple/Simple.svc" />

wsdl:port>

wsdl:service>

The host name “mycomputer.private.mydomain.com” is automatically picked up by WCF. In the real production environment, you would want to use a public host name or even an IP address in the address. Here are a few steps that can help you to make the change:

1) Change IIS Site Binding

WCF populates service base addresses based on IIS site bindings. The format of a site binding looks like “::”. For HTTP, the default site binding for the default web site is “:80:”. This means that the service can receive messages from any IP addresses for the host and it uses “weak” wildcard for address registration. You need to change it to be an “exact” host name for the site so that it shows up in your service base address. You can use the IIS utility tool adsutil.vbs (or appcmd.exe on IIS7) to achieve that.

You can query your current site bindings for the default web site as following:

cscript //nologo %systemdrive%\inetpub\adminscripts\adsutil.vbs get W3SVC/1/ServerBindings

Here is the command to change it:

cscript //nologo %systemdrive%\inetpub\adminscripts\adsutil.vbs set W3SVC/1/ServerBindings “:80:www.fancydomain.com”

You can also change it from IIS Manager UI. For HTTPS, the following command would work:

cscript //nologo %systemdrive%\inetpub\adminscripts\adsutil.vbs set W3SVC/1/SecureBindings“:443:www.fancydomain.com”

2) Recycle the AppDomain

Once you changed IIS settings, WCF does not automatically pick up the changes from IIS Metabase. You have to recycle the current AppDomain for the virtual application. There are a few different ways to do that:

· Change web.config file for the virtual application

· Kill w3wp.exe process

· Run “iisreset.exe”

3) Query the WSDL

Now when you query the WSDL of your service, you will see the new addresses:

<wsdl:service name="SimpleService">

<wsdl:port name="BasicHttpBinding_ISimpleContract"binding="tns:BasicHttpBinding_ISimpleContract">

<soap:address location="http://www.fancydomain.com /simple/Simple.svc" />

wsdl:port>

wsdl:service>

How to use .asmx extension to handle WCF requests?

For backward compatibility, WCF supports easy server-side migration from ASMX to WCF. This is good news for existing ASMX customers. Generally, the clients of ASMX may have server Urls hard-coded with the extension “.asmx”. For example, here is a sample Url:

http://www.myserver.com/foo/MyService.asmx

After installing WCF on the box, you can let WCF to handle the same client requests. Here are the steps about how to achieve this:

Replace BuildProvider for ASMX

You need to use the WCF service build provider for .asmx extension by seting the following in the web.config file of your virtual application:

<system.web>

<compilation>

<buildProviders>

<remove extension=".asmx" />

<add extension=".asmx" type="System.ServiceModel.Activation.ServiceBuildProvider, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

buildProviders>

compilation>

system.web>

When WCF is running in the Mixed Transport mode (instead of AspNetCompatibility mode), WCF would intercept the request based on the BuildProvider information for the extension.

Replace HttpHandler for ASMX

If you are running WCF in AspNetCompatibility mode, you would also need to change the HttpHandler s for .asmx to the WCF HttpHandler. On IIS6, you just need to have something as following in your config:

<system.web>

<httpHandlers>

<remove path="*.asmx" verb="*">remove>

<add path="*.asmx" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

validate="false" />

httpHandlers>

system.web>

On IIS7, things are different. IIS7 introduces two different HTTP pipelines: Integrated and Classic. The latter works similar as IIS6 in the way that all of the managed requests go through the ASP.NET ISAPI filter. When this happens, the HttpModules and HttpHandlers defined in web.config files would be invoked for the corresponding requests.

When the virtual application is running in the Integrated mode, however, the modules and handlers defined in web.config files under the section are totally ignored. All of the requests are handled straightforward by IIS7. So you need to make sure that you have integrated handlers defined for the corresponding extensions. We can set the following in the web.config of the virtual application to achieve this:

<system.webServer>

<handlers>

<remove name="WebServiceHandlerFactory-Integrated"/>

<add name="MyNewAsmxHandler" path="*.asmx" verb="*"type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"preCondition="integratedMode,runtimeVersionv2.0" />

handlers>

<validation validateIntegratedModeConfiguration="false" />

system.webServer>

The section is actually rooted in %windir%\system32\inetsrv\config\applicationhost.config instead of in the root web.config in %windir%\Microsoft.Net\Framework{64}\v2.0.50727\config. The element takes the “name” as the key instead of the “path” as we did to the section. You must specify “validateIntegratedModeConfiguration” to false to make IIS happy.

Correct SOAP Actions

Once you configured above settings, you can create a .asmx file which looks exactly as a .svc file. For example, you can have the following content:

<% @ServiceHost language = "c#" Factory="HelloWorld.SimpleServiceHostFactory" %>

Now you can browse your service with an .asmx extension. At this point, all requests will go through happily into WCF channel stack.

One last thing that you need to be aware is that you need to make sure your WCF service is backward compatible to ASMX so that ASMX clients can communicate with it. Basically you need to use the interoperable binding such as BasicHttpBinding. And you need to make sure the request/response SOAP actions are expected for ASMX clients. Here is an example:

[ServiceContract(Name = "RequestReplyService", Namespace ="http://myoldasmxworld.org/")]

public interface IRequestReplySyncServiceAsmx

{

[OperationContract(IsOneWay = false, Action ="http://myoldasmxworld.org/HelloRequestReply")]

string HelloRequestReply(string text);

}

It is compatible to the following ASMX web service:

[WebService(Name = "MyAsmxService", Namespace ="http://myoldasmxworld.org/")]

public class AsmxRequestReplyService

{

[WebMethod]

public string HelloRequestReply(string text)

{

// Implementation

}

}