2

I am trying to create windows service using dotnet worker project that starts up rest-api, I am using kestrel server for this purpose:

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;

namespace TurkisisService
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
            kestrelStarted=false;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                if(!kestrelStarted) {
                    kestrelStarted=true;
                    var host = new WebHostBuilder()
                    .UseKestrel()
                    .UseStartup<Startup>()
                    .Build();

                    var task = Task.Run(() => {
                        host.Run();
                    });
                }
                await Task.Delay(1000, stoppingToken);
            }
        }

        private bool kestrelStarted;
    }

    public class Startup {

        public void Configure(IApplicationBuilder app){
            app.Run(context => {
                
                return context.Response.WriteAsync("Hello world!");
            });
            
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
    }
}

I used these packages:

<Project Sdk="Microsoft.NET.Sdk.Worker">

<PropertyGroup>
  <TargetFramework>net5.0</TargetFramework>
  <UserSecretsId>dotnet-turkisis_service-9216353E-18A1-49B4-8CAB-E939439FF992</UserSecretsId>
  <RootNamespace>turkisis_service</RootNamespace>
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
  <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
  <PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
</ItemGroup>

The console displays these lines of logs:

Now listening on: http://localhost:5000 Now listening on: https://localhost:5001

but when I open the url on web browser: http://localhost:5000, also https://localhost:5001 returns empty, they are display: ERR_EMPTY_RESPONSE

  • did you check the other URL with `https://`? and the same port with `https://`? – Yılmaz Durmaz Jan 01 '22 at 08:56
  • yes, other url https:// open internet and same port with https:// also empty response – Mayas Faraj Jan 01 '22 at 10:42
  • please check the answer in [kestrel-returns-empty-response-to-httpcontext](https://stackoverflow.com/questions/65011002/kestrel-returns-empty-response-to-httpcontext). it seems pretty much similar to your case with its `async/await` part to startup code – Yılmaz Durmaz Jan 01 '22 at 11:15
  • and I also see you are pretty new, welcome to stackoverflow. try to extract keywords in errors you get and see if there are similar posts to your problems before posting new ones ;) I hope the link above helps you. if not feel free to tell more. and by the way, edit your post to tell `htps://` is working and fix the typo, missing `E`, in `ERR_EMPTY_RESPONS` – Yılmaz Durmaz Jan 01 '22 at 11:20
  • my bad sorry, seeing low reputation numbers I cant help but think OPs are new to the site. you are almost 5 years old here :) – Yılmaz Durmaz Jan 01 '22 at 17:21
  • thanks for your advices, I had checked the url but it is not solve the problem – Mayas Faraj Jan 01 '22 at 23:15
  • You need to remove the `Kestrel` package and update the Project Sdk to `Microsoft.NET.Sdk.Web` - see this question for details https://stackoverflow.com/q/66829853/2309376 – Simply Ged Jan 02 '22 at 05:14
  • NOTE: If you add a breakpoint to the `return context.Response.WriteAsync("Hello world!");` line you will see it is throwing an exception. – Simply Ged Jan 02 '22 at 05:17
  • I was trying some variations on your problem. it seems you need `web context` to be able to send/receive web requests. start with changing project sdk from `Worker` to `Web` as suggested above and see if you can get what you want. you may also want to try starting a web project and adding worker in it, instead of starting a worker project and adding web in it. after all, a rest-api is basically a web backend. – Yılmaz Durmaz Jan 02 '22 at 06:16
  • thanks for all I will try to change the project type but it will not solve the problem, I need windows service – Mayas Faraj Jan 05 '22 at 22:17

0 Answers0