将 IEnumerable<T> 传递给 Blazor WASM 中的 API 方法

passing IEnumerable<T> to API method in Blazor WASM

请问,如何在 Blazor WASM 项目中使用 Http.GetFromJsonAsync 传递 IEnumerable 参数? 这是我在剃刀组件中的代码:

IEnumerable<WAGPiattValidePerUtente> piattValidePerUtente;

dipendenti = await Http.GetFromJsonAsync<IEnumerable<WAGDipendentiAttivitaNGiorniPrec>>($"WAGDipendentiAttivitaNGiorniPrecService/ByDaySottrDataPiattaforme/{(short)7}/{dataRif.ToString("yyyyMMdd")}/{piattValidePerUtente}");

在我的 API 控制器中,代码是:

        [HttpGet("ByDaySottrDataPiattaforme/{giorniDaSottrarre}/{dataRif}/{piattaforme}")]
    public async Task<ActionResult<IEnumerable<WAGDipendentiAttivitaNGiorniPrec>>> GetWAGDipendentiPiattAttivitaNGiorniPrec(short giorniDaSottrarre, string dataRif, IEnumerable<WAGDipendentiAttivitaNGiorniPrec> piattaforme)
    {
      //call a store procedure...
    }

调用该方法时出现此错误: 加载资源失败:服务器响应状态为 415() 不支持的媒体类型

有人可以帮我吗?

how can I pass an IEnumerable parameter using Http.GetFromJsonAsync in a Blazor WASM project?

Failed to load resource: the server responded with a status of 415 () Unsupported Media Type

通常我们使用路由数据和查询字符串值来传递简单类型的数据。

要实现通过路由数据将 IEnumerable 参数传递给操作方法的要求,您可以尝试实现和使用自定义模型绑定器,如下所示。

public class MyModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // ...
        // implement it based on your actual requirement
        // code logic here
        // ...

        var model = new List<WAGPiattValidePerUtente>();

        if (bindingContext.ValueProvider.GetValue("piattaforme").FirstOrDefault() != null)
        {
            model = JsonSerializer.Deserialize<List<WAGPiattValidePerUtente>>(bindingContext.ValueProvider.GetValue("piattaforme").FirstOrDefault());
        }


        bindingContext.Result = ModelBindingResult.Success(model);
        return Task.CompletedTask;
    }
} 

将其应用于操作参数

[HttpGet("ByDaySottrDataPiattaforme/{giorniDaSottrarre}/{dataRif}/{piattaforme}")]
public async Task<ActionResult<IEnumerable<WAGDipendentiAttivitaNGiorniPrec>>> GetWAGDipendentiPiattAttivitaNGiorniPrec(short giorniDaSottrarre, string dataRif,
    [ModelBinder(BinderType = typeof(MyModelBinder))]
IEnumerable<WAGPiattValidePerUtente> piattaforme)
{
    //call a store procedure...

从客户端应用发出请求

var piattValidePerUtente_data = Uri.EscapeDataString(JsonSerializer.Serialize(piattValidePerUtente));

dipendenti = await Http.GetFromJsonAsync<IEnumerable<WAGDipendentiAttivitaNGiorniPrec>>($"WAGDipendentiAttivitaNGiorniPrecService/ByDaySottrDataPiattaforme/{(short)7}/{dataRif.ToString("yyyyMMdd")}/{piattValidePerUtente_data}");

测试结果