Xabaril / AspNetCore.Hashids

Not predictable ids library for ASP.NET Core APIs.
Apache License 2.0
113 stars 15 forks source link

HashIds not working after adding custom Output formatter #16

Open zehanjura opened 2 years ago

zehanjura commented 2 years ago

I am using Hashids library in my .NET 6 API to encode int values into string values in my model before sending it off to the API caller. The library is currently working fine.

Recently I have a requirement to provide pascal cased json from the API (default it was returning camel case). In order to achieve this I have gone in the path of sending an Accept header with a custom value and added an output formatter to handle the pascal case conversion.

public class PascalCaseFormatter : SystemTextJsonOutputFormatter { public PascalCaseFormatter(JsonSerializerOptions jsonSerializerOptions) : base(jsonSerializerOptions) { SupportedMediaTypes.Clear(); SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json;profile=pascal")); } }

then registered it in Startup.cs

`services.AddHashids(setup => { setup.Salt = Configuration["HashConfiguration:Salt"]; setup.MinHashLength = Convert.ToInt32(Configuration["HashConfiguration:MinHashLength"]); setup.Alphabet = Configuration["HashConfiguration:Alphabet"]; });

services.AddControllers(options => { options.OutputFormatters.Add( new PascalCaseFormatter(new JsonSerializerOptions { PropertyNamingPolicy = null })); });`

In the accept header if I send as application/json;profile=pascal I get pascal cased json result for any model which does not have a hashid converter in it. When I have a model as below, then an error is thrown from the hashids library mentioning that the service provider is not found.

public class ApplicantAccountVm { [JsonConverter(typeof(HashidsJsonConverter))] public int ApplicantAccountId { get; set; } }

Result for this model,

image

What should I do to register hashid in this situation?