Xabaril / AspNetCore.Hashids

Not predictable ids library for ASP.NET Core APIs.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

HashIds not working after adding custom Output formatter

zehanjura opened this issue · comments

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?