Convert Web API to use Self Hosting

后端 未结 1 1102
难免孤独
难免孤独 2020-12-23 14:54

I am trying to convert an existing ASP.NET Web API project (currently hosted in IIS) into one that can use the SelfHost framework. I\'m a bit fuzzy on the actual details but

相关标签:
1条回答
  • 2020-12-23 15:17

    I recently had to convert a Web API project into a self-hosted service using OWIN (on Visual Studio 2013). I did that as follows:

    1. Manually added Program.cs and Startup.cs files at the root of the project. Both files containing code as described here: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api.

    2. Went to the properties of the Web API project. On the "Applications" section, I stated "Output Type" as "Console Application", and set the "Program" class as the "Startup object".

    Although not required, I slightly modified the using block within Program.Main() to look as follows:

    // Start OWIN host 
    using (WebApp.Start<Startup>(url: baseAddress)) 
    { 
      // Create HttpCient and make a request to api/values 
      HttpClient client = new HttpClient(); 
      var response = client.GetAsync(baseAddress + "api/values").Result; 
    
      if (response != null)
      {
        Console.WriteLine("Information from service: {0}", response.Content.ReadAsStringAsync().Result);
      }
      else
      {
        Console.WriteLine("ERROR: Impossible to connect to service");
      }
    
      Console.WriteLine();
      Console.WriteLine("Press ENTER to stop the server and close app...");
      Console.ReadLine();
    } 
    

    Finally, instead of calling config.Routes.MapHttpRoute() multiple times within Startup.Configuration(), you can refer to the routes you already wrote for the Web API:

    // Configure Web API for self-host. 
    var config = new HttpConfiguration();
    WebApiConfig.Register(config);        
    app.UseWebApi(config); 
    
    0 讨论(0)
提交回复
热议问题