CustomModelBinder.cs 1.14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace MEU.API.MiddleWare
{
    public class CustomModelBinder: IModelBinder 
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            
            var request = bindingContext.HttpContext.Request;

            using (var reader = new StreamReader(request.Body, Encoding.UTF8))
            {
                try
                {
                    var bodyString = reader.ReadToEnd();
                    var resultObject = JsonConvert.DeserializeObject<object>(bodyString);
                    RequestParams.setParam(bindingContext.FieldName, resultObject);
                    var result = JsonConvert.DeserializeObject(bodyString, bindingContext.ModelType);
                    bindingContext.Result = ModelBindingResult.Success(result);
                }
                catch (Exception ex)
                {
                }
              
            }

            return Task.CompletedTask;
        }
    }
}