Search code examples
iis-6windows-7-x64owin-middleware

Self-Hostable and IIS-hostable OWIN project


I would like to modify my solution to run under a self-hosted OWIN instance, but I also need it to run under http://localhost when necessary.

How should I structure my Startup class to be recognised by both?

Currently, I have the Web API project set as a Console Application with the project URL as http://localhost:2746 and this is my Startup class:

[assembly: OwinStartup(typeof(Startup))]
namespace Books
{
    public class Startup
    {
        public static void Main(string[] args)
        {
            const int port = 2746;
            var url = $"http://localhost:{port}/";

            using (WebApp.Start<Startup>(new StartOptions(url) { ServerFactory = "Microsoft.Owin.Host.HttpListener" }))
            {
                var client = new HttpClient { BaseAddress = new Uri(url) };
                Console.ReadLine();
            }
        }

        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration httpConfiguration = new HttpConfiguration();
            WebApiConfig.Register(httpConfiguration);
            app.Use<CustomExceptionMiddleware>().UseWebApi(httpConfiguration);
            app.UseFileServer(StaticFileConfig.Build());
        }
    }
}

I also have this in the web.config:

<add key="owin:AutomaticAppStartup" value="false" />

Solution

  • use two projects:

    1. create a web project for the api controllers. this project can host in iis
    2. create another console project as the self-host, this project need refer the web project, now you can share the WebApiConfig/Controllers to this project

    ps: OwinStartup attribute indicate the entrypoint for iis, but i use the traditional global.asax to initial the api config. so that the Startup class can also share the config from WebApiConfig