首页 > 解决方案 > 注册为windows服务时无法访问netcore服务

问题描述

我尝试使用 netcore 作为 Windows 服务运行一个简单的 Web api 示例。但是,如果我将它作为控制台应用程序运行,那很好,我可以通过浏览器访问它。但是在将 netcore 应用程序安装为服务后,它无法通过浏览器访问。有什么我想念的想法吗?

这是我的代码:

public class Program
{
    public static void Main(string[] args)
    {
        // following works if I use Run() and execute on commandline
        // instead of calling RunAsService()
        CreateWebHostBuilder(args).Build().RunAsService();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

如您所见……这里没有什么特别的。其实这是Visual Studio在使用asp.netcore骨架时生成的代码。

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }

使用生成的控制器,这应该返回一些值作为 api/values 下的文本打印输出。所以我只调用https://localhost:5001/api/values

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody] string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

不知何故,这可以用作控制台,但不能用作服务。

我使用命令

dotnet publish -c Release -r win10-x64 --self-contained

因此在发布文件夹(连同依赖项)中创建了一个 WebApplication1.exe(根据测试项目名称)。

然后我将此exe注册为服务

sc create "TestService" binPath= "C:\Projects\Playground\WebApplication1\bin\Release\netcoreapp2.1\win10-x64\publish\WebApplication1.exe"

然后打电话

sc start "TestService"

它似乎工作。但是,当我尝试通过 url 访问服务时,我没有得到任何响应。

这里缺少什么?

标签: c#asp.net-core.net-corewindows-services

解决方案


当我的服务在本地系统帐户下运行时,我会出现此问题。如果我将服务下的管理员添加为登录帐户,一切正常。

对我来说似乎是权限问题。


推荐阅读