Thursday, December 12, 2019

Host Web Core trên WindowsService

Tạo 1 project web hoặc web API Core.

class Program sửa thành

public class Program
    {
        public static void Main(string[] args)
        {

            CreateWebHostBuilder(args).Build().RunAsService();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .UseStartup<Startup>().
                UseUrls("http://localhost:5000");
    }

Mở file project, sửa lại giống như sau sau

<PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <RuntimeIdentifiers>win10-x64;</RuntimeIdentifiers>
    <OutputType>Exe</OutputType>
  </PropertyGroup>

Chuyển vào thư mục project, chạy lệnh sau:
dotnet publish --configuration Release --self-contained -r win10-x64

Mở cmd lần nữa để chạy lệnh cài đặt service

sc create WindowsServiceHosted binPath= "C:\WindowsServiceHosted\bin\Debug\netcoreapp2.1\win7-x64\publish\WindowsServiceHosted.exe"

Chạy sc start WindowsServiceHosted để start service.
Chạy sc description WindowsServiceHosted "This is the description of the service.." để gán mô tả cho service

http://localhost:5000 để chạy web

No comments: