[英]Compiler Error Consuming Web API Call
I need to implement a webapi call into a legacy ASP.Net Web Forms application. 我需要对旧版ASP.Net Web窗体应用程序实施webapi调用。
I know not all of the usings are need for this method but they are for other methods on the page i included on the off chance that one of them is causing the problem. 我知道并非所有使用方法都需要此方法,但是我将其包含在页面上的其他方法上,这其中一个正在引起问题。
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;
}
When I try to compile my application I get the following error at the emphisized line: 当我尝试编译我的应用程序时,在强调行出现以下错误:
Error 19 The 'await' operator can only be used within an async method. 错误19'await'运算符只能在异步方法中使用。 Consider marking this method with the 'async' modifier and changing its return type to 'Task< string>'. 考虑使用'async'修饰符标记此方法,并将其返回类型更改为'Task <string>'。
I am trying to implement a solution similar to the one found in this question but it is failing. 我正在尝试实现一种与该问题中发现的解决方案相似的解决方案,但失败了。 I need to call the WebAPI Method, and return part of the result as a string... not a Task< String> 我需要调用WebAPI方法,并将结果的一部分作为字符串返回...而不是Task <String>
The error is straightforward. 该错误很简单。 You must have an async
method to use the await
keyword. 您必须具有async
方法才能使用await
关键字。 Your return value will automatically be wrapped in a Task as a result by the compiler. 您的返回值将由编译器自动包装在Task中。 Note that the .Result
can be changed to an await as well. 请注意, .Result
也可以更改为await。 Here's the Microsoft documentation on the async/await keywords 这是有关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.