1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

.Net6 Controller DateOnly型のAPIのエラー

Last updated at Posted at 2022-01-24

環境

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 にアクセスすると

スクリーンショット 2022-01-24 002042.png

こんな感じのエラーになります。文字に起こすと

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が取得できました.

Page

こちらのAPI をBlazor側が受け取るとエラーになるな。。。

うーん解決方法がわからない。

最後に

ぼちぼちがんばるでー

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?