Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9699

.Net6 Controller DateOnly型のAPIのエラー

$
0
0
環境 C# .Net6 EFCore6 Blazor はじめに API作成なんぞただの文字列だからエラーなんて起こらないだろうとおもってたら DateOnly型でエラーになったのその原因の解決方法を書いておきます。 まだ日本語記事がどこにもなさそうなので 原因 モデル /Shared/Models/Renter.cs namespace BlazorApp.Shared.Models { public class Renter { [Display(Name = "生年月日")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateOnly? BirthDate { get; set; } 略 コントローラー using ChintaiApp.Server.Data; using ChintaiApp.Shared.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BlazorApp.Server.Controllers { [Route("api/[controller]")] [ApiController] public class RentersController : ControllerBase { private readonly AppDbContext context; public RentersController(AppDbContext context) { this.context = context; } [HttpGet] public async Task<ActionResult<List<Renter>>> ListAsync() { var renters = await context.Renters.ToListAsync(); return Ok(renters); } } } これを https://localhost:7029/api/renters にアクセスすると こんな感じのエラーになります。文字に起こすと NotSupportedException: Serialization and deserialization of 'System.DateOnly' instances are not supported. とか NotSupportedException: Serialization and deserialization of 'System.DateOnly' instances are not supported. The unsupported member type is located on type 'System.Nullable`1[System.DateOnly]'. Path: $.BirthDate ですね 要は、.Net がDateOnly型を標準でサポートしていないから。 解決 これですね https://www.nuget.org/packages/DateOnlyTimeOnly.AspNet/ パッケージマネージャーコンソール PM> Install-Package DateOnlyTimeOnly.AspNet Server/Program.cs // 以下を追加 builder.Services .AddControllers(options => options.UseDateOnlyTimeOnlyStringConverters()) .AddJsonOptions(options => options.UseDateOnlyTimeOnlyStringConverters()); これ先ほどのURLにアクセスするとJSONが取得できました. 最後に ぼちぼちがんばるでー

Viewing all articles
Browse latest Browse all 9699

Trending Articles