Решено - C# Сервис HttpClient reponse null - PullRequest
0 голосов
/ 19 апреля 2020

Я просмотрел все возможные посты и не нашел ни одного решения, которое бы работало на меня (больше нет проблем с импортом), пожалуйста, помогите. : (

Я создаю windows службу в c#, и мне нужно каждый раз вызывать веб-службу и проверять, должна ли она что-то делать. (Сбор инструкций)

Я прикрепляю весь код:

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 верный, и он регистрируется в журнале «Ответ ОК», поэтому он вводит «если», но никогда не получает чтобы получить результат:

log image

Спасибо!

1 Ответ

0 голосов
/ 20 апреля 2020

Это была моя вина. код был в порядке, но у него был метод для регистрации журналов в формате строки. Поэтому, когда я получил '{', метод интерпретировал его как передаваемый ему параметр. Я сохраню пост для других.

Спасибо всем за помощь.

...