WebApp.Start() calls Startup Configuration twice

2019-08-29 19:17发布

问题:

I'm hosting Web API and SignalR client in a Windows service. Any code after the WebApp.Start is getting executed twice. Also requests to the Web APIs are also received twice. Below is my sample code, in this TestSignalRService:3 and traces in configuration are getting printed twice. My App.config is also pretty basic and doesn't have any settings.

public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }

    IDisposable SignalR;
    HttpSelfHostServer server;
    protected override void OnStart(string[] args)
    {
        Start();
    }

    protected override void OnStop()
    {
        server.CloseAsync();
        SignalR.Dispose();
    }

    public void Start()
    {
        Trace.WriteLine("TestSignalRService:1");

        var config = new HttpSelfHostConfiguration("http://localhost:9090");
        config.Routes.MapHttpRoute(
                          name: "DefaultApi",
                          routeTemplate: "api/{controller}/{id}",
                          defaults: new { id = RouteParameter.Optional }
                          );

        server = new HttpSelfHostServer(config);


        server.OpenAsync().Wait();
        Trace.WriteLine("TestSignalRService:2");

        string url = "http://*:9191/";
        try
        {
            SignalR = WebApp.Start<TestStart>("http://*:9191/");
            Trace.WriteLine("TestSignalRService:3");
        }
        catch (Exception e)
        {
            Trace.WriteLine("TestSignalRService::Exception in starting Signal R " + e.Message);
        }

    }
}

class TestStart
{
    public void Configuration(IAppBuilder app)
    {
        Trace.WriteLine("TestSignalRService::Startup configuration");

        Trace.WriteLine("TestSignalRService::Startup configuration 1");
        app.Map("/signalr", map =>
        {
            //map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration
            {  EnableDetailedErrors = true
            };               
            map.RunSignalR(hubConfiguration);
        });            
        Trace.WriteLine("TestSignalRService::Startup configuration 3");
    }
}

My service is not restarting as the traces above the WebApp.Start are not getting printed twice. Anything that is after the WebApp.Start call is getting executed twice. What could be the reason for this and how to fix this? Please help, I'm using OWIN self host for the first time.

回答1:

The law 'complain to a stranger - and find the answer immediately' works for me :3

public void Configure()
{
    // code here executes once per application starts

    app.Run(async context => 
    {
        // code here executes once per http request
    });
}

My web app starts twice due to the default requests from browser are '/' and '/favicon.png'.

Thanks juunas answer for a clue)



标签: c# owin