MVC Core的自定義模型綁定IModelBinder

在.net framework時MVC5下我們自定義模型綁定是繼承DefaultModelBinder來重寫BindModel實現的

如代碼:

/*
 * 描述:自定義ModelBinder進行字符串輸入的處理去空格
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyMis.MvcHelper {
	public class StringModelBinder:DefaultModelBinder {
		public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
			object value =  base.BindModel(controllerContext, bindingContext);
			//處理string類型數據
			if (value is string) {
				string strValue = (string)value;
				string newValue = strValue.Trim();
				return newValue;
			}
			else {
				return value;
			}
		}
	}
}

然後在Global文件中註冊下

            //對自定義的ModelBinder進行
            ModelBinders.Binders.Add(typeof(string), new StringModelBinder());

但是在.net core下使用的方式卻變了,差別還是有點的。

mvc core沒有提供對應的類DefaultModelBinder讓我們來繼承重寫,所以只有自己創建了

1.創建DefaultModelBinder類以供其他自定義的方法來繼承,重寫BindModelAsync

using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyMis.Web.MvcHelper {
    public class DefaultModelBinder : IModelBinder {
        public virtual Task BindModelAsync(ModelBindingContext bindingContext) {
            var modelName = bindingContext.ModelName;
            //根據名稱獲取傳遞的值
            ValueProviderResult ValueResult = bindingContext.ValueProvider.GetValue(modelName);
            //從請求的參數集合中,拿到第一個參數
            string value = ValueResult.FirstValue;
            bindingContext.Result = ModelBindingResult.Success(value);
            return Task.CompletedTask;
        }
    }
}

2.實現StringModelBinder通過繼承剛纔的DefaultModelBinder重寫BindModelAsync來實現,如果要實現NumberModelBinder方法也一樣,繼承後重寫就行了

/*
 * 描述:自定義ModelBinder進行字符串輸入的處理去空格
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyMis.MvcHelper {
	public class StringModelBinder:DefaultModelBinder {
		public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
			object value =  base.BindModel(controllerContext, bindingContext);
			//處理string類型數據
			if (value is string) {
				string strValue = (string)value;
				string newValue = strValue.Trim();
				return newValue;
			}
			else {
				return value;
			}
		}
	}
}

3.在mvc core下注冊需要實現IModelBinderProvider纔可以,這跟mvc 5又有了很大的不同,我們需要自己來實現此代碼

using Microsoft.AspNetCore.Mvc.ModelBinding;
using MyMis.MvcHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyMis.Web.MvcHelper {
    public class ModelBinderProvider : IModelBinderProvider {
        public IModelBinder GetBinder(ModelBinderProviderContext context) {
            if (context.Metadata.ModelType == typeof(string)) {
                return new StringModelBinder();
            }
            else if (context.Metadata.ModelType == typeof(int)) {
                return new NumberModelBinder();
            }
            return null;
        }
    }
}

代碼時候好後,如何來使用呢,我們需要註冊下

            services.AddMvc(m=> {
                //註冊到集合的第一個
                m.ModelBinderProviders.Insert(0, new ModelBinderProvider());
            });

這樣就可以使用了,當然也有其他方法來註冊實現,如在在實體類頭上加入特性

[ModelBinder(BinderType = typeof(StringModelBinder))]

    [ModelBinder(BinderType = typeof(StringModelBinder))]
    public class Userinfo
    {
        public int id { get; set; }
        public string name { get; set; }
    }

還可以在方法參數上加上特性[ModelBinder(BinderType = typeof(StringModelBinder))]

  public IActionResult Index([ModelBinder(BinderType = typeof(StringModelBinder))]Userinfo info)
        {
        }

參考:

https://docs.microsoft.com/zh-cn/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-3.1

https://blog.csdn.net/weixin_43458389/article/details/88619558

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章