如何从现有的Windows服务启动AspNetCore应用程序

时间:2018-08-23 15:33:32

标签: c# asp.net-core windows-services

我有一个现有的Windows服务。目标是拥有REST接口以与此服务进行通信。我认为仅制作一个ASP.NET Core Web应用程序(请参见屏幕截图)并在我现有的服务中简单地启动整个过程可能是一个好主意。然后他们可以共享相同的IOC容器,依此类推。

enter image description here

然后我在Object上注册了服务

启动服务(附加到调试过程)时,在输出窗口中出现错误:

sc create s1 binPath = "pathgoeshere"

我将整个示例放在GitHub上:

https://github.com/SuperSludge/aspnetcoreService

有人曾经做过这样的事情吗?我完全走错了路吗?将整个Windows服务重写为ASP.NET Core App是否更容易?

2 个答案:

答案 0 :(得分:2)

Do you need ASP.NET core application or just expose REST endpoints ? I am thinking you are trying to use it for the benefits of the library. If latter is true,   
 I have done a similar thing where we have exposed some REST endpoints hosted in our legacy Windows service through "Microsoft.Owin.Hosting". This looks exactly like the ASP.NET WEPAPI

    1) In your windows service, you can start the WebApp like

           //WEBAPI URL
           private const string WEBAPI_BASEADDRESS = "https://+:{port number}/";
           // declare a Idisposable variable
           private IDisposable webAPI;
           //Use Microsoft Owin's library to start it up
           webAPI = WebApp.Start<Startup>(url: WEBAPI_BASEADDRESS);

    //above "Startup" is a class you would declare in your other class library (see below number 2)


    2) You can create a new C# class library with a class named "Startup"  and use the system.Web.Http "Httpconfiguration" class as below

    /// <summary>
    /// Web API startup method
    /// </summary>
    public class Startup
    {
        private const string TOKEN_URL = "/api/token";
        private const string BASE_URL = "/api/{controller}/{id}";
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {

            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: BASE_URL,
                defaults: new { id = RouteParameter.Optional }
            );

            appBuilder.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString(TOKEN_URL),
                Provider = new CustomAuthorizationServerProvider()
            });
            appBuilder.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //Swagger support
            SwaggerConfig.Register(config);
            //appBuilder.UseCors(CorsOptions.AllowAll);
            appBuilder.UseWebApi(config);
        }
    }

    3) Above code has a CustomAuthorizationProvider where you can declare your own Custom OAuth Authorization and do any kind of authentication you want as below

        public class CustomAuthorizationServerProvider : OAuthAuthorizationServerProvider

    and override the "`public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)`"

4) Then you can just spin up WebAPI controllers
    [Authorize]
    public class XXXController : ApiController
    {
}

Hope this helps . Let me know if something is not clear.

答案 1 :(得分:1)

如果要在服务中包含REST Api,则应在服务项目中添加WebApi,而不要在其他项目中。因此,在这种情况下,我认为您不能使用Asp.Net Core。

使用Owin在服务内部启动Rest Api,然后在另一个线程中运行服务。

// declare baseUrl in confing file by ex
// Startup is your Startup class
using (WebApp.Start<Startup>(baseUrl))
{
     System.Console.WriteLine($"Listening on {baseUrl}");
     Thread.Sleep(Timeout.Infinite);
}

Imo,您应该有另一个服务来运行此API,因此可以使用Asp.Net.Core。

Windows服务执行一些逻辑,WebApi使用相同的Business Api来干扰相同的Db。