【问题标题】:C# Service HttpClient reponse null已解决 - C# Service HttpClient 响应 null
【发布时间】:2020-04-19 11:35:33
【问题描述】:

我浏览了所有可能的帖子,但没有找到任何适合我的解决方案(没有更多看到导入的混乱),请帮助。 :(

我正在用 c# 构建一个 Windows 服务,我需要每 X 次调用一个 Web 服务并检查它是否必须做某事。 (收集说明)

我附上整个代码:

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Reflection;
using System.ServiceProcess;
using System.Timers;
using System.Text;

namespace TestServiceCreateFile
{

public partial class Service1 : ServiceBase
{
    /* Config values */
    int CheckRobotStatusTimerMills = 10000;
    static string MachineKey = "";

    private static readonly HttpClient client = new HttpClient();
    EventLog EventLog = new System.Diagnostics.EventLog();

    public Service1()
    {
        this.ServiceName = "BotBrainExecutor";
        this.EventLog.Source = this.ServiceName;
        this.EventLog.Log = "Application";

        ((ISupportInitialize)(this.EventLog)).BeginInit();
        if (!EventLog.SourceExists(this.EventLog.Source))
        {
            EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log);
        }
        ((ISupportInitialize)(this.EventLog)).EndInit();

    }

    protected override void OnStart(string[] args)
    {
        LoadConfig();

        Timer timer = new Timer();
        timer.Interval = CheckRobotStatusTimerMills;
        timer.Elapsed += (s, e) => MainFunctionAsync(s, e);
        timer.Start();


        base.OnStart(args);
    }

    private string URLGetOrdersOrch = "http://localhost:8080/testing?machinekey=" + MachineKey;
    public async Task MainFunctionAsync(object sender, ElapsedEventArgs args)
    {
        LogLine("Start" + " " + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"));

        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = await httpClient.GetAsync(URLGetOrdersOrch);

        if (response.IsSuccessStatusCode)
        {
            LogLine("Response OK");

            LogLine(await response.Content.ReadAsStringAsync());
        }
        else
        {
            LogLine((int)response.StatusCode + " " + response.ReasonPhrase);
        }

    }

问题是Http的结果是正确的并且它在日志中注册'Response OK',所以它正在输入'if',但它永远不会收集结果:

谢谢!

【问题讨论】:

  • 您好!感谢您的答复!我之前尝试过,结果相同,我更新了问题以澄清。
  • await response.Content.ReadAsStringAsync() 返回什么?

标签: c# windows rest service ws


【解决方案1】:

这完全是我的错。 代码很好,但它有一种方法来注册具有字符串格式的日志。因此,当我收到一个“{”时,该方法将其解释为传递给它的参数。 我会把帖子留给别人看。

感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 2021-09-22
    • 2016-12-20
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    相关资源
    最近更新 更多