Error launching Angular in .Net Core as Windows Service

0

I am trying to launch Angular in .Net Project as self-hosted windows service. The error I am getting while accessing on chrome is:

HTTP Error 502.5 - Process Failure

Common causes of this issue: The application process failed to start The application process started but then stopped The application process started but failed to listen on the configured port

Program.cs

public class Program
{
public static void Main(string[] args)
{
  try
  {
    var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
    var pathToContentRoot = Path.GetDirectoryName(pathToExe);

    IWebHost host;

    if (Debugger.IsAttached || args.Contains("console"))
    {
      Debugger.Launch();
      host = WebHost.CreateDefaultBuilder()
              .UseContentRoot(Directory.GetCurrentDirectory())
              .UseStartup<Startup>()
              .UseUrls("http://localhost:60967/")
              .Build();
      host.Run();
    }
    else
    {
      host = WebHost.CreateDefaultBuilder(args)
              .UseContentRoot(pathToContentRoot)
              .UseStartup<Startup>()
              .Build();
      host.RunAsService();
    }
  }
  catch (Exception ex)
  {
    throw;
  }
}

On checking the event viewer, the error shown is:

Application 'MACHINE/WEBROOT/APPHOST/API.WEBAPI' with physical root 'C:\Projects\MIRCOM\Api\Dev\Api\' failed to start process with commandline 'c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\web tools\projectsystem\VSIISExeLauncher.exe -argFile "C:\Users\gaurav.saxena\AppData\Local\Temp\tmpA00F.tmp"', ErrorCode = '0x80004005' : 0.

The strange thing is it keeps referencing my Api.

The API as self-hosted works great, but the UI doesn't.

c#
asp.net
.net
asp.net-core
asked on Stack Overflow Nov 23, 2019 by Gauravsa • edited Nov 23, 2019 by theduck

1 Answer

0

There is a difference in the working directory when running an application as a windows service. The working directory, in that case, is %WinDir%\System32.

In this case, you are calling

UseContentRoot(Directory.GetCurrentDirectory())

which will return %WinDir%\System32 to use as the Content Root. Of course, your files won't be found there, resulting in the error above.

Try using

System.Reflection.Assembly.GetEntryAssembly().Location

or

AppDomain.CurrentDomain.BaseDirectory

to resolve the correct directory and set the correct contentRoot.

answered on Stack Overflow Nov 28, 2019 by Thomas Luijken

User contributions licensed under CC BY-SA 3.0