110,549
社区成员
发帖
与我相关
我的任务
分享
services.AddMvc(options =>
{
//需要插入到第一条,内置默认是匹配到合适的Provider就不会在向下继续绑定;如果添加到末尾,即不会调用到我们实现的
options.ModelBinderProviders.Insert(0, new StringTrimModelBinderProvider(options.InputFormatters));
});
[ModelBinder(BinderType = typeof(StringTrimModelBinderProvider(options.InputFormatters)))]
public class TestModel
{
//....
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
namespace Model
{
public class StringTrimModelBinderProvider : IModelBinderProvider
{
private readonly IList<IInputFormatter> _formatters;
public StringTrimModelBinderProvider(IList<IInputFormatter> formatters)
{
_formatters = formatters;
}
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
var mvcoptions = context.Services.GetService<IOptions<MvcOptions>>();
//添加需要自定义模型类名
List<string> M = new List<string>();
M.Add(typeof(TestModel).Name);
M.Add(typeof(HouseModel).Name);
M.Add(typeof(HouseBuildingModel).Name);
M.Add(typeof(HouseRoomModel).Name);
M.Add(typeof(HouseSourceModel).Name);
M.Add(typeof(HouseTypeModel).Name);
string ModelName =context.Metadata.ModelType.Name;
if (context == null)
throw new ArgumentNullException(nameof(context));
if (!M.Contains(ModelName))
return null;
if (!context.Metadata.IsComplexType && context.Metadata.ModelType == typeof(string))
{
//简单类型
var loggerFactory = (ILoggerFactory)context.Services.GetService(typeof(ILoggerFactory));
return new SimpleStringTrimModelBinder(context.Metadata.ModelType);
}
else if (context.BindingInfo.BindingSource != null &&
context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Body))
{
//通过[FromBody]绑定的
return new BodyStringTrimModelBinder(_formatters, context.Services.GetRequiredService<IHttpRequestStreamReaderFactory>());
}
return null;
}
}
}