-1

我正在为我的 REST API 创建 Web 客户端,并且我想在我的表中添加一个包含异步函数结果的字段。

@foreach(Product item in products)
        {
            <tr>
                <th>@item.Name</th>
                <th>@item.Amount</th>
                <th>@GetUnit(item.UnitID).Result</th>
                <th>@item.PriceNetto</th>
            </tr>
        }


async Task<string> GetUnit(Guid id)
{
    string a = "https://localhost:5001/api/Units/";
    a += id.ToString();
    var temp = await Http.GetJsonAsync<Unit>(a); //it fails here
    return temp.Name;
}

简而言之,我有一个产品列表,列表中的项目具有“UnitID”属性,我用它来发出 GET 请求。当我.Result在我的异步函数结果之后在代码中的任何位置放置时,Visual Studio 的调试器只需跳过负责调用 API 的行并“砖”整个应用程序,没有任何错误或异常。然后我必须重新启动项目。

我试图创建仅用于返回的第二个函数,GetUnit(id).Result但它什么也没提供。我试图返回整个 Unit 对象,然后在表中,GetUnit(item.UnitID).Name但它只是代表对象(我猜......)。我似乎只需要这样做,.Result但是当我这样做时它不起作用。

我的 API 是用 .Net Core 2.2 制作的,我的客户端是用 .Net Core 3.0(Blazor 模板)制作的。这是一个错误还是我不能那样做?谢谢。

4

2 回答 2

2

您不需要这样做。我建议在异步操作中调用它,如下所示:
剃刀专注于视图,控制器/模型专注于数据。

public async Task<IActionResult> SomeAction(Guid id)
{
    var products = ..;
    foreach (var item in products)
    {
        p.UnitID = await GetUnit(item.UnitID);
    }
    return View(products);
}

private async Task<string> GetUnit(Guid id)
{
    string a = "https://localhost:5001/api/Units/";
    a += id.ToString();
    var temp = await Http.GetJsonAsync<Unit>(a); //it fails here
    return temp.Name;
}

public class Product 
{
    public string Name { get; set; }    
    public decimal Amount { get; set; } 
    public string UnitID { get; set; }  
    public string PriceNetto { get; set; }  
}
于 2019-11-04T03:00:49.127 回答
0

IMO,你不能那样做。在 blazor 中,你可以获取所有数据OnInitializedAsync。将所有数据存储在Name字符串列表中,并在基于视图的索引中显示列表数据。例如:

@code {

    private List<string> listItems = new List<string>();

    protected override async Task OnInitializedAsync()
    {
        //get products

        foreach (var product in products)
        {
            string a = "https://localhost:5001/api/Units/";
            a += product.UnitID.ToString();
            var temp = await Http.GetJsonAsync<Unit>(a); 

           listItems.Add(temp.Name);
        }
    }
}

剃刀

@{  int i = 0;}
@foreach(Product item in products)
    {
        <tr>
            <th>@item.Name</th>
            <th>@item.Amount</th>
            <th>  @listItems[i] </th>
            <th>@item.PriceNetto</th>
        </tr>
        i++;
    }
于 2019-11-06T02:52:40.620 回答