
正文
ASP.NET Core 下自定义模型绑定,去除字符串类型前后的空格
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
效果图:
01

02




直接贴代码了:
NoTrim
public class NoTrimAttribute : Attribute
{
}
我们自定义的模型绑定提供程序
/// <summary>
/// 自定义的“天空”模型绑定提供程序
/// </summary>
public class MyModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context)); if (!context.Metadata.IsComplexType && context.Metadata.ModelType == typeof(string))
{
//简单类型
var loggerFactory = (ILoggerFactory)context.Services.GetService(typeof(ILoggerFactory));
return new SkySimpleTypeModelBinder(new SimpleTypeModelBinder(context.Metadata.ModelType, loggerFactory));
}
if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType)
{
//复杂类型
var propertyBinders = context.Metadata.Properties
.ToDictionary(modelProperty => modelProperty, modelProperty => context.CreateBinder(modelProperty));
var loggerFactory = (ILoggerFactory)context.Services.GetService(typeof(ILoggerFactory));
return new SkyComplexTypeModelBinder(propertyBinders, loggerFactory);
}
return null;
}
}
注册服务
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
}); //注册自定义的模型绑定
services.AddControllersWithViews(
options => options.ModelBinderProviders.Insert(, new MyModelBinderProvider())
).AddNewtonsoftJson();
services.AddRazorPages();
}
}
谢谢浏览!






