【发布时间】:2015-03-27 16:18:40
【问题描述】:
我需要在旧版 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' 运算符只能在异步方法中使用。 考虑使用“异步”修饰符标记此方法并更改 它的返回类型为'Task'。
我正在尝试实施类似于this question 中的解决方案,但它失败了。我需要调用 WebAPI 方法,并将结果的一部分作为字符串返回...而不是 Task
【问题讨论】:
-
这是一个非常开放和关闭的案例。你不明白什么?当这个错误弹出时,你是否对 async/await 进行过研究?
-
如果我的调用有误,那很好,那么我如何使用 API 调用并从方法中返回一个字符串?
-
我正在尝试实现类似于这个问题的解决方案:stackoverflow.com/questions/19448690/… 但结果失败了。
标签: c# asp.net asp.net-web-api