0

I've created program in C# Worker Service .NET 7.0. This program listening all incoming GET request and save this requests as URI and URL into Log.txt file. I used Titanium Web Proxy to listen all incoming requests from server. Program is working correctly but problem apear when im trying to run it as windows service. To do this im publishing my program into folder, next using command prompt Im creating service choosing .exe file from published folder and starting process with "sc start ServiceName" command. Service is running but its not working at all.

Here is my Program.cs code:

using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Hosting;
using Serilog.Extensions.Logging;

namespace WorkerService5
{
    public class Program
    {
        static async Task Main(string[] args)
        {
            IHost host = Host.CreateDefaultBuilder(args)
                .ConfigureServices(services =>
                {
                    services.AddHostedService<Worker>();
                })
                .UseWindowsService()
                .UseSerilog()
                .Build();

            await host.RunAsync();
        }
    }
}
Here is my Worker.cs code:
using System.Net;
using Titanium.Web.Proxy;
using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Models;
using Serilog;
using Microsoft.Extensions.Hosting;

namespace WorkerService5
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private readonly IHostApplicationLifetime _hostApplicationLifetime;

        public Worker(ILogger<Worker> logger, IHostApplicationLifetime hostApplicationLifetime)
        {
            _logger = logger;
            _hostApplicationLifetime = hostApplicationLifetime;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken) => Task.Run(async () =>
        {
            try
            {
                var proxyServer = new ProxyServer(userTrustRootCertificate: false);

                proxyServer.BeforeRequest += OnRequest;

                var explicitEndPoint = new ExplicitProxyEndPoint(IPAddress.Any, 8000, true);

                proxyServer.AddEndPoint(explicitEndPoint);

                proxyServer.Start();

                foreach (var endPoint in proxyServer.ProxyEndPoints)
                    _logger.LogInformation("Listening on '{0}' endpoint at Ip {1} and port: {2} ",
                        endPoint.GetType().Name, endPoint.IpAddress, endPoint.Port);

                proxyServer.SetAsSystemHttpProxy(explicitEndPoint);

                // Console.ReadLine();

                stoppingToken.Register(() =>
                {
                    proxyServer.BeforeRequest -= OnRequest;
                    proxyServer.Stop();
                });

                await Task.Delay(Timeout.Infinite, stoppingToken);
            }

            catch (Exception)
            {
                throw;
            }

        });

        private async Task OnRequest(object sender, SessionEventArgs e)
        {
            var filePath = @"E:\LogiusService\Logs\log.txt";

            Log.Logger = new LoggerConfiguration()
                .WriteTo.File(filePath, rollingInterval: RollingInterval.Day, shared: true)
                .CreateLogger();

            string requestedUrl = e.HttpClient.Request.Host;
            Console.WriteLine("Requested URL: " + requestedUrl);
            Log.Information($"Requested URL: " + requestedUrl);

            string requestedUri = e.HttpClient.Request.RequestUri.AbsoluteUri;
            Console.WriteLine("Requested URI: " + requestedUri);
            Log.Information($"Requested URI: " + requestedUri);
        }
    }
}

Any ideas how can i run it as Windows Background Service? Cheers!

  • 1. Make sure your working directory is as expected. 2. Ensure [failures aren't ignored](https://blog.stephencleary.com/2020/05/backgroundservice-gotcha-silent-failure.html). 3. [Shut down the app when the service is done](https://blog.stephencleary.com/2020/06/backgroundservice-gotcha-application-lifetime.html). – Stephen Cleary Feb 15 '23 at 11:56
  • @StephenCleary I implemented your soultions to my code, but my service still do nothing. Edited code in post. Maybe im doing something wrong, probably yes. You'll have to excuse me, I'm an intern. – Tomasz Florczyk Feb 15 '23 at 13:16
  • Are you not getting any logs at all? – Stephen Cleary Feb 15 '23 at 14:03
  • Nothing and nothing, event viewer just telling me that my service is started. Nothing is added to my log.txt file. – Tomasz Florczyk Feb 15 '23 at 15:20
  • I reread what you wrote, also i ask chat GPT how to fix this problem. I added couple changes in worker.cs and its working now. Working code above – Tomasz Florczyk Feb 16 '23 at 08:43

0 Answers0