带有主页的Web API自托管主机

时间:2018-03-09 08:44:45

标签: c# asp.net-web-api windows-services

我有一个Windows服务需要一个Web管理门户来管理和控制配置,并且应该由同一个Windows服务公开(我不想使用IIS)。

我尝试过Web API自我主机,但我无法为我的端口设置启动页面。我尝试了下面的代码,请帮我设置自我管理的Web API的主页。

    const string BaseAddress = "http://localhost:8080";

    static void HostAPI()
    {
        Console.WriteLine("Starting service");
        HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(BaseAddress);
        config.Routes.MapHttpRoute(
             "Default",
             "{controller}/{action}/{id}" }
        );

        using (HttpSelfHostServer server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();
            Console.WriteLine($"Service started at {BaseAddress}");
        }
    }

1 个答案:

答案 0 :(得分:1)

您应该对主页执行操作并从中返回html。

public class HomeController : ApiController
{
    [HttpGet]
    [Route]
    public HttpResponseMessage Get()
    {
        var response = new HttpResponseMessage();
        // add your homepage html here
        response.Content = new StringContent("<html><body>Your Home Page</body></html>");
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
       return response;
    }
}