Обновление текста метки использует только часть данного текста - PullRequest
0 голосов
/ 16 мая 2018

Я новичок в C # и безуспешно пытаюсь обновить текст метки после http-запроса от API. Я делаю это, как показано ниже:

 private void buttonGenerateKey_Click(object sender, EventArgs e)
{
    var apiKey = getApiKey();
    Console.WriteLine("Your API Key: " + apiKey); //-> Your API Key: Knh4dH4d8rtWfgXr5
    labelApiKeyText.Text = "Your API Key: " + apiKey; //-> Your API Key:
    Console.WriteLine("Label Content: " + labelApiKeyText.Text); //-> Your API Key: Knh4dH4d8rtWfgXr5
    labelApiKeyText.ForeColor = Color.ForestGreen;
    labelApiKeyText.Refresh();
}

// --- Get an API Key
private string getApiKey()
{
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("http://localhost:61128/StationService.svc/");
    HttpResponseMessage response = httpClient.GetAsync("key").Result;
    var ApiKeyString = response.Content.ReadAsStringAsync();
    var ApiKey = JsonConvert.DeserializeObject<string>(ApiKeyString.Result);
    return ApiKey;
}

Я вижу правильный текст в консоли, но на этикетке отображается только «Ваш ключ API:»

Даже после попытки использовать BackgroundWorker у меня не получилось. Я что-то не так делаю?

1 Ответ

0 голосов
/ 18 мая 2018

Измените свой код на следующий, посмотрите, поможет ли он.

private async string getApiKey()
{
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("http://localhost:61128/StationService.svc/");
    HttpResponseMessage response = await httpClient.GetAsync("key");
    if(response==null)
    {
        // something went wrong
    }
    var ApiKeyString = await response.Content.ReadAsStringAsync();
    var ApiKey = JsonConvert.DeserializeObject<string>(ApiKeyString);
    return ApiKey;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...