效果圖:
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(); } }
謝謝瀏覽!