繁体   English   中英

无法从视图中的异步方法返回值

[英]cannot return value from async method in view

我正在尝试从async html帮助程序返回值,但它给出以下字符串而不是所需的值。

“System.Threading.Tasks.Task + WhenAllPromise`1 [System.Decimal]”

方法:

public async static Task<decimal> CalculateCurrency(this HtmlHelper helper, decimal amount, string from, string country)
    {
        if (await getValue(country))
        {
            string fromCurrency = string.IsNullOrEmpty(from) ? "USD" : from;
            string toCurrency = country;
            WebClient client = new WebClient();
            string url = string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", fromCurrency.ToUpperInvariant(), toCurrency.ToUpperInvariant());
            Stream response = await client.OpenReadTaskAsync(url);
            StreamReader reader = new StreamReader(response);
            string yahooResponse = await reader.ReadLineAsync();
            response.Close();
            if (!string.IsNullOrWhiteSpace(yahooResponse))
            {
                string[] values = Regex.Split(yahooResponse, ",");
                if (values.Length > 0)
                {
                    decimal rate = System.Convert.ToDecimal(values[1]);
                    string res = string.Format("{0:0.00}", rate * amount);
                    return decimal.Parse(res);
                 }
            }
            return decimal.Zero;
        }
        return decimal.Zero;
    }

呼叫HTML助手:

@Html.CalculateCurrency(22, "USD", "EUR")

视图不支持异步方法。 因此,作为结果,您将获得默认.ToString()函数的结果类型,该结果实际上返回的只是类型名称。

选项:

  • 将代码移至控制器,并使用await从异步顶级(非子级)操作中调用。 通过模型或ViewBag传递数据以进行查看
  • 如果必须从视图或子操作中调用它,则转换为真实的同步代码
  • 如果不可能,请尝试.Result ,但要.Result死锁。 请参阅等待与任务。等待-死锁? 有关详细信息/链接。

注意:将async代码移至子操作将无济于事。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM