Compartilhar via


Global configuration for WebAPI services to add custom extensions

 

When you create a WebAPI service, you must configure it in code by adding to the generated Register method. There does not seem to be a way to establish a policy-based configuration for ALL WebAPI services on the box. After coming up empty on Bing (and Google!) I decided to read up on Katana and found a hook at the OWIN host level which can be used to inject configuration onto these WebAPI apps.

 

First, write a simple class as follows and make it strongly-typed by signing it and then GAC it (you will need to pull in OWIN and WebAPI libs via NuGet).  

 

 

namespace WebApi

{

    publicclassWebApiConfiguration

    {

        publicvoid Configuration(IAppBuilder app)

        {

            var config = GlobalConfiguration.Configuration;

            ConfigureAuth(app);

            ConfigureExtensions(config);

        }

 

        publicstaticvoid ConfigureExtensions(HttpConfiguration config)

        {

            config.Filters.Add(newMyAuthFilter());

            config.MessageHandlers.Add(newMyDelegatingHandler());

            config.Filters.Add(newMyExceptionFilterAttribute());

            config.Filters.Add(newMyActionFilterAttribute());

            config.Formatters.Add(newMyMediaTypeFormatter());

        }

 

        publicvoid ConfigureAuth(IAppBuilder app)

        {

            app.UseCookieAuthentication(newCookieAuthenticationOptions());

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        }

 

    }

 

… other classes left out for brevity.

 

The main method is Configuration which gets called by the OWIN host – but only if it finds a particular setting in the appSettings configuration. What was surprising (to me) is that you can have a ‘global’ set of appSettings in the global web.config file. Just add the following to the web.config file located in c:\windows\microsoft.net\framework\v4.0.30319\config:

 

  <appSettings>

                <add key="owin:appStartup" value="WebApiConfiguration, WebApiExtension, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fc3a6ca1f8e86de8" />

    </appSettings>

 

Now any WebAPI app on that box will automatically pull in your custom extensions so you can have your own hooks into these apps. From an enterprise perspective, you can plugin your own tracing, exception handling, Action filters, authentication etc. And the app developer needs not do anything special so there is nothing new to learn. It was pointed out to me that this will setting will override the Startup class in the app. In our case this is a good thing as we want to enforce certain behaviors on the app.

 

BTW I used Web API 2.2 for this POC.