ASP.NET Core 下自定义模型绑定,去除字符串类型前后的空格
2024-09-01 01:04:30
效果图:
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();
}
}
谢谢浏览!
最新文章
- C#如何创建泛型类T的实例
- CentOS 5.8/6.7若干优化
- uva 242
- 七. CSS字体
- elasticsearch 基础语句
- 吴恩达深度学习笔记1-神经网络的编程基础(Basics of Neural Network programming)
- 手动设定统计数据 set_table_stats
- Chap3:区块链的衍生技术[《区块链中文词典》维京&;甲子]
- openresty + lua 2、openresty 连接 redis,实现 crud
- Windows 网卡超过序列
- hdu 4112 Break the Chocolate 贪心
- arcgis server 无法手动删除切片
- 毕业设计总结(1)-canvas画图
- 监听器(Listener)学习(二)在开发中的常见应用
- 转!java产生不重复随机数
- C# 6新特性简单总结
- 201621123033 《Java程序设计》第10周学习总结
- Unicode字符集和多字节字符集关系
- 不可见类有抽象父类,spring配置子类bean,注入父类,aop就可以切父类的方法
- web结对项目