代码改变世界

ASP.NET Core 下自定义模型绑定,去除字符串类型前后的空格

2019-04-24 20:26  音乐让我说  阅读(1363)  评论(1编辑  收藏  举报

效果图:

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(0, new MyModelBinderProvider())
            ).AddNewtonsoftJson();
            services.AddRazorPages();
        }
}

 

 

 

 

谢谢浏览!