Files
monorepo/LCU.API.Internal.Document/LCU.Library.Internal.DocumentModels/Converter/JsonQueryBinder.cs
T
2026-03-13 09:11:35 -05:00

49 lines
1.3 KiB
C#

using System;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace LCU.Library.Internal.DocumentModels.Converter
{
public class FromJsonQueryAttribute : ModelBinderAttribute
{
public FromJsonQueryAttribute()
{
BinderType = typeof(JsonQueryBinder);
}
}
public class JsonQueryBinder : IModelBinder
{
public JsonQueryBinder()
{
}
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.FieldName).FirstValue;
if (value == null)
{
return Task.CompletedTask;
}
try
{
var parsed = JsonSerializer.Deserialize(
value,
bindingContext.ModelType,
new JsonSerializerOptions(JsonSerializerDefaults.Web)
);
bindingContext.Result = ModelBindingResult.Success(parsed);
}
catch (Exception e)
{
bindingContext.Result = ModelBindingResult.Failed();
}
return Task.CompletedTask;
}
}
}