简体   繁体   English

从 .net windows 服务调用宁静的 api 服务似乎不起作用

[英]Calling a restful api from .net windows service seems to be not working

I have created a windows service application which is supposed to make a call to a restful api each one minute.我创建了一个 windows 服务应用程序,它应该每分钟调用一个安静的 api。 I am actually running the API on my localhost device and putting a breakpoint to detect if the api being called, but nothing was received.我实际上是在我的本地主机设备上运行 API 并设置断点来检测是否调用了 api,但没有收到任何消息。

I have then copied exact same code to a console application and it seems being working as perfect.然后,我将完全相同的代码复制到控制台应用程序中,它似乎工作得非常完美。 I am really new to windows services and I don't know if have any restrictions for calling an api within a service, so could you please tell me where is the issue我对 windows 服务真的很陌生,我不知道在服务中调用 api 是否有任何限制,所以请告诉我问题出在哪里

================================================================= ==================================================== ================

this function will be called each 1 minute此 function 将每 1 分钟调用一次

    public async Task<DateTime> GetLastUpdatedDate(string branchName)
    {
        var VpsBaseUrl = System.Configuration.ConfigurationManager.AppSettings["VpsBaseUrl"];
        HttpResponseMessage response = await client.GetAsync($"{VpsBaseUrl}/api/transactions/{branchName}");
        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<DateTime>(json);
            Console.WriteLine(result.ToString());
            return result;
        }
        else
        {
            return DateTime.Now.AddDays(-10);
        }
    }

========================================================================== ==================================================== =========================

   protected override void OnStart(string[] args)
    {
        //Create a new Timer with Interval set to seconds(1 Minutes).
        System.Timers.Timer aTimer = new System.Timers.Timer(1 * 60 * 1000);
        aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
        aTimer.Start();
    }

    protected override void OnStop(){ }

    //object source, System.Timers.ElapsedEventArgs e
    private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
    {
        try
        {
            var task = Task.Run(async () =>
            {
                var x =  await tProxy.GetLastUpdatedDate("branch1");
                LogHelper.AppendToLogInfo(x.ToString());
            });
        }
        catch(Exception ex)
        {
            LogHelper.AppendToLogError(ex.Message);
        }
    }

Let me clear you few points.让我澄清你几点。

  1. There is no different between calling API from Window Service or Window Form or Any Web API. There is no different between calling API from Window Service or Window Form or Any Web API.

  2. Context is important if account under which API execute does not have permission.如果执行 API 的帐户没有权限,则上下文很重要。 (This could be second thing you can check). (这可能是您可以检查的第二件事)。

  3. One thing I will correct is我要纠正的一件事是

     var task = Task.Run(async () => { var x = await tProxy.GetLastUpdatedDate("branch1"); LogHelper.AppendToLogInfo(x.ToString()); }); task.Wait(); // It seems that you are missing this.

if you don't wait then it goes to next line and in your case it will get out of scope so possibly garbage collected.如果您不等待,那么它会转到下一行,在您的情况下,它将退出 scope ,因此可能会被垃圾收集。

It's possible that your configuration is not being read correctly in the Win32 service. Win32 服务中可能未正确读取您的配置。 Win32 services have their working directory set differently than console applications. Win32 服务的工作目录设置不同于控制台应用程序。

Try putting the following line of code at the top of your Main method:尝试将以下代码行放在Main方法的顶部:

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM