Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从现有windows服务启动AspNetCore应用程序_C#_Asp.net Core_Windows Services - Fatal编程技术网

C# 如何从现有windows服务启动AspNetCore应用程序

C# 如何从现有windows服务启动AspNetCore应用程序,c#,asp.net-core,windows-services,C#,Asp.net Core,Windows Services,我有一个现有的windows服务。目标是有一个REST接口与此服务通信。我认为制作一个ASP.NET核心Web应用程序(参见屏幕截图)并在现有服务中启动整个过程可能是个好主意。然后他们可以共享同一个IOC容器等等 然后我向sc create s1 binPath=“pathgoesher” 启动服务(连接到进程以进行调试)时,输出窗口中出现错误: Exception thrown: 'System.DllNotFoundException' in Microsoft.AspNetCore.Se

我有一个现有的windows服务。目标是有一个REST接口与此服务通信。我认为制作一个ASP.NET核心Web应用程序(参见屏幕截图)并在现有服务中启动整个过程可能是个好主意。然后他们可以共享同一个IOC容器等等

然后我向sc create s1 binPath=“pathgoesher”

启动服务(连接到进程以进行调试)时,输出窗口中出现错误:

Exception thrown: 'System.DllNotFoundException' in Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.dll
The thread 0x5250 has exited with code 0 (0x0).
Exception thrown: 'System.DllNotFoundException' in mscorlib.dll
Exception thrown: 'System.DllNotFoundException' in mscorlib.dll
'WindowsService1.exe' (CLR v4.0.30319: WindowsService1.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceProcess.resources\v4.0_4.0.0.0_de_b03f5f7f11d50a3a\System.ServiceProcess.resources.dll'. Module was built without symbols.
Exception thrown: 'System.DllNotFoundException' in mscorlib.dll
Exception thrown: 'System.DllNotFoundException' in mscorlib.dll
The thread 0x4fa0 has exited with code 0 (0x0).
Microsoft.AspNetCore.Server.Kestrel: Warning: Unable to bind to http://localhost:5000 on the IPv4 loopback interface: 'Die DLL "libuv": Das angegebene Modul wurde nicht gefunden. (Ausnahme von HRESULT: 0x8007007E) kann nicht geladen werden.'.
Exception thrown: 'System.DllNotFoundException' in Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.dll
The thread 0x58c4 has exited with code 0 (0x0).
Exception thrown: 'System.DllNotFoundException' in mscorlib.dll
Exception thrown: 'System.DllNotFoundException' in mscorlib.dll
Exception thrown: 'System.DllNotFoundException' in mscorlib.dll
Exception thrown: 'System.DllNotFoundException' in mscorlib.dll
Microsoft.AspNetCore.Server.Kestrel: Warning: Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Die DLL "libuv": Das angegebene Modul wurde nicht gefunden. (Ausnahme von HRESULT: 0x8007007E) kann nicht geladen werden.'.
Exception thrown: 'System.IO.IOException' in Microsoft.AspNetCore.Server.Kestrel.Core.dll
Exception thrown: 'System.IO.IOException' in mscorlib.dll
Exception thrown: 'System.IO.IOException' in mscorlib.dll
Exception thrown: 'System.IO.IOException' in mscorlib.dll
Microsoft.AspNetCore.Server.Kestrel: Critical: Unable to start Kestrel.
我将整个示例放在GitHub上:


有人做过这样的事吗?我是不是完全走错了路?将整个windows服务重写为ASP.NET核心应用程序是否更容易

如果希望在服务中使用REST Api,则应将WebApi添加到服务项目中,而不是其他项目中。所以,在这种情况下,我认为您不能使用Asp.NETCore

使用Owin在服务内启动restapi,并在另一个线程中运行服务

// 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);
}
//通过ex在确认文件中声明baseUrl
//Startup是您的Startup类
使用(WebApp.Start(baseUrl))
{
System.Console.WriteLine($“侦听{baseUrl}”);
Thread.Sleep(Timeout.Infinite);
}
在我看来,您应该有另一个服务来运行此API,这样,您就可以使用Asp.Net.Core

Windows服务执行一些逻辑,而WebApi使用相同的业务Api来干扰相同的数据库。

您需要ASP.NET核心应用程序还是只公开REST端点?我想你是为了图书馆的利益而使用它。如果后者是真的,
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.
我也做了类似的事情,我们通过“Microsoft.Owin.Hosting”公开了遗留Windows服务中托管的一些REST端点。这看起来很像ASP.NET WEPAPI 1) 在windows服务中,您可以像这样启动WebApp //WEBAPI URL 私有常量字符串WEBAPI_BASEADDRESS=“https://+:{port number}/”; //声明Idisposable变量 私有IDisposable webAPI; //使用Microsoft Owin的库启动它 webAPI=WebApp.Start(url:webAPI\u BASEADDRESS); //上面的“Startup”是您将在其他类库中声明的类(请参见下面的数字2) 2) 您可以使用名为“Startup”的类创建一个新的C#类库,并使用system.Web.Http“Httpconfiguration”类,如下所示 /// ///webapi启动方法 /// 公营创业 { private const string TOKEN_URL=“/api/TOKEN”; 私有常量字符串BASE_URL=“/api/{controller}/{id}”; //此代码配置Web API。启动类被指定为类型 //WebApp.Start方法中的参数。 公共无效配置(IAppBuilder appBuilder) { //为自主机配置Web API。 HttpConfiguration config=新的HttpConfiguration(); config.SuppressDefaultHostAuthentication(); 添加(新的HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); config.maphttpAttribute路由(); config.Routes.MapHttpRoute( 名称:“DefaultApi”, routeTemplate:BASE\u URL, 默认值:新建{id=RouteParameter.Optional} ); 使用OAuthAuthorizationServer(新的OAuthAuthorizationServerOptions { AllowInsecureHttp=true, TokenEndpointPath=新路径字符串(TOKEN_URL), Provider=新的CustomAuthorizationServerProvider() }); 使用OAuthBeareAuthentication(新的OAuthBeareAuthenticationOptions()); //昂首阔步的支持 SwaggerConfig.Register(配置); //appBuilder.UseCors(CorsOptions.AllowAll); appBuilder.UseWebApi(配置); } } 3) 上面的代码有一个CustomAuthorizationProvider,您可以在其中声明自己的自定义OAuth授权,并执行您想要的任何类型的身份验证,如下所示 公共类CustomAuthorizationServerProvider:OAuthAuthorizationServerProvider 并重写“`public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext)`” 4) 然后,您可以启动WebAPI控制器 [授权] 公共类XXX控制器:ApiController { } 希望这有帮助。如果有什么不清楚,请告诉我。
看来您的方法应该是可行的。您看过Windows服务文档中的主机ASP.NET核心吗@是的,我看过这个。问题是我有两个项目。一个现有的Windows服务和一个新的Rest API项目。正如我所提到的,如果我能够获得Asp.NET核心API的所有好处,但将其托管在现有项目中,那将是非常棒的。否则,我将不得不安装、注册和维护2个windows服务。或者(正如我提到的)在ASP.NET核心应用程序中重写整个服务。我最终使用了两个服务。无论如何,“一个服务”的方法仍然更可取。Owin将是一个选项,但我更喜欢“标准”方式,并使用“内置”解决方案。也许有一天这是可能的。在那之前,我接受这个答案。