【问题标题】:Compiler Error Consuming Web API Call使用 Web API 调用的编译器错误
【发布时间】: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

【问题讨论】:

标签: c# asp.net asp.net-web-api


【解决方案1】:

错误很简单。您必须有一个 async 方法才能使用 await 关键字。作为编译器的结果,您的返回值将自动包装在 Task 中。请注意,.Result 也可以更改为等待。 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;
}

【讨论】:

  • 我需要使用调用并返回一个字符串而不是一个任务。我所做的研究表明这是这样做的方法。
  • 如果您不想使用 await,那么只需将注释掉的行更改为 var data = response.Content.ReadAsStringAsync().Result;,但从长远来看,获取有关异步代码如何工作的更多信息将为您提供更好的服务。跨度>
  • 如果你想要字符串,在调用函数中使用GetToken().Result,但我的最后一条评论会给你同样的结果。
  • 我不能只做 JsonConvert.DeserializeObject(data.Result); ?
  • 这就是我在此回复下的第一条评论中所说的,只是没有保留您的临时变量。
猜你喜欢
  • 2012-11-26
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
相关资源
最近更新 更多