49 lines
1.3 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|