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

 

 

 

 

謝謝瀏覽!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM