using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Text; using System.Threading.Tasks; namespace WcfControlMonitorWebLib { /// /// 指定参数仅来自传入的实体成员 /// [AttributeUsage(AttributeTargets.Parameter)] public class FromMemberAttribute : ModelBinderAttribute { /// /// 构造函数 /// public FromMemberAttribute() : base(typeof(ModelBinder)) { } /// /// 实体绑定器 /// private class ModelBinder : IModelBinder { /* * 实现 Microsoft.AspNetCore.Mvc.ModelBinding.IModelBinder.BindModelAsync(ModelBindingContext bindingContext) 方法 * add for TJBS */ public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var json = string.Empty; using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body)) { json = await reader.ReadToEndAsync(); } var value = JsonHelper.Deserialize(json)[bindingContext.FieldName]; if (value != null) { bindingContext.Result = ModelBindingResult.Success(value.ToObject(bindingContext.ModelType)); } bindingContext.HttpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(json)); } } } }