[英]Compiler Error Consuming Web API Call
我需要對舊版ASP.Net Web窗體應用程序實施webapi調用。
我知道並非所有使用方法都需要此方法,但是我將其包含在頁面上的其他方法上,這其中一個正在引起問題。
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
private string GetToken(string Username, string IpAddress)
{
string result = string.Empty;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(SSOApiUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result;
if (response.IsSuccessStatusCode)
{
***var data = await response.Content.ReadAsStringAsync();***
var token = JsonConvert.DeserializeObject<GetSSOTokenResponse>(data);
result = token.Token;
}
return result;
}
當我嘗試編譯我的應用程序時,在強調行出現以下錯誤:
錯誤19'await'運算符只能在異步方法中使用。 考慮使用'async'修飾符標記此方法,並將其返回類型更改為'Task <string>'。
我正在嘗試實現一種與該問題中發現的解決方案相似的解決方案,但失敗了。 我需要調用WebAPI方法,並將結果的一部分作為字符串返回...而不是Task <String>
該錯誤很簡單。 您必須具有async
方法才能使用await
關鍵字。 您的返回值將由編譯器自動包裝在Task中。 請注意, .Result
也可以更改為await。 這是有關async / await關鍵字的Microsoft文檔
private async Task<string> GetToken(string Username, string IpAddress)
{
string result = string.Empty;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(SSOApiUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<GetSSOTokenResponse>(data);
result = token.Token;
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.