I need to implement a webapi call into a legacy ASP.Net Web Forms application.
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. Consider marking this method with the 'async' modifier and changing its return type to '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>
The error is straightforward. You must have an async
method to use the await
keyword. Your return value will automatically be wrapped in a Task as a result by the compiler. Note that the .Result
can be changed to an await as well. Here's the Microsoft documentation on the async/await keywords
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.