简体   繁体   中英

How do I include JsonOptions in WebAssemblyHostBuilder on a Blazor .NET 6 web app?

I am working with .NET 6 and have a UI and API which is using the new DateOnly type.

Following the answer from this article:

System.NotSupportedException: Serialization and deserialization of 'System.DateOnly' instances are not supported

I successfully implemented a JsonConverter for this on the API inside my Program.cs class with:

builder.Services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter()));

I am unsure how to register the JsonConverter in a Blazor .NET 6 web application as AddControllers() MVC nuget not included and when I have tried pulling in nuget packages for these causes conflicts with razor with Blazor/MVC as you'd expect.

This is my Program.cs in Blazor web app with my failed attempts commented out:

....
// TODO: adding DateOnly Json Converter to services ...
//builder.Services.AddRazorPages().AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter()));
//builder.Services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter()));
//builder.Services.Configure<JsonOptions>(options => options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter()));

await builder.Build().RunAsync();
EDIT

So this looks like the way to go about adding it, however I am stumped on which NuGet package I need to pull in for the Microsoft.AspNetCore.Http.Json namespace.

https://learn.microsoft.com/en-us/do.net/api/microsoft.as.netcore.http.json?view=as.netcore-6.0

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.AspNetCore.Http.Json;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

builder.Services.Configure<JsonOptions>(options => options.SerializerOptions.Converters.Add(new DateOnlyJsonConverter()));

使用语句

I've tried adding these NuGet packages but doesnt appear to contain that namespace

安装的nuget包

EDIT 2

Turns out the namespace that has JsonOptions in (Microsoft.AspNetCore.Http.Json) is in https://www.nuget.org/packages/Microsoft.AspNetCore.App.Ref but I cant add the nuget package as its.netcore SDK for internal implementations, which makes sense now why the WebApi app has it out the box.

So back to the drawing board on how I need to register the json options in Program.cs

Any help would be greatfully appreciated.

Thanks in advance,

Rob

After going down this rabbit-hole, it looks like HttpClient doesn't let you configure this globally, from the back of this answer:

How to set default json serialization settings for HttpClient (WinForms)

Best work-around I found to save duplication of JsonOptions per api call was to write a generic function for GetJsonFromAsync of T

public class HttpClientWithOptions : IHttpClientWithOptions
{
    private readonly HttpClient _httpClient;

    private readonly string _baseUrl = "https://localhost:1234/MyAPI";

    private readonly JsonSerializerOptions _options;

    public HttpClientWithOptions(HttpClient httpClient)
    {
        this._httpClient = httpClient;
        _options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        _options.Converters.Add(new DateOnlyJsonConverter());
    }

    public async Task<dynamic?> GetFromJsonAsync<T>(string path)
    {
        return await _httpClient.GetFromJsonAsync<T>($"{_baseUrl}{path}", _options);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM