net-core Action返回IAsyncEnumerable的案例和JSON的处理

[HttpGet("asyncsale")]
public async IAsyncEnumerable<Product> GetOnSaleProductsAsync()
{
    var products = _repository.GetProductsAsync();

    await foreach (var product in products)
    {
        if (product.IsOnSale)
        {
            yield return product;
        }
    }
}

 JSASP.NET Core Web API 

JSASP.NET Core Web API 中的 ON 修补程序支持基于 Newtonsoft.Json 并需要 Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包。 若要启用 JSON Patch 支持,请:

  • 安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包。

  • 调用 AddNewtonsoftJson。 例如:

    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddControllers()
        .AddNewtonsoftJson();
    
    var app = builder.Build();
    
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();

    默认情况下,内置帮助程序方法 ControllerBase.Ok 返回 JSON 格式的数据:

  • [HttpGet]
    public IActionResult Get() =>
        Ok(_todoItemStore.GetList());

    默认情况下,ASP.NET Core 支持以下媒体类型:

    • application/json
    • text/json
    • text/plain
posted @ 2023-05-30 10:12  vba是最好的语言  阅读(40)  评论(0编辑  收藏  举报