编写自定义的模型绑定器

接手了一个重构旧项目的任务,后端是PHP的,前端用的几个零散的东西。重构的原则是 前端基本不动,后端改形成 dotnetcore 。前端

过程基本顺利,遇到的一个问题的解决方式以为值得说一下。问题是这样:一个页面的某一个接收参数,有从A页面来的,也有B页面来的,可是A和B页面提交过来的格式是不同的,A页面是正常的字符,B页面过来的是Unicode 编码,%u5ba2%u6237 的这种。
接收的地方大概是这样:后端

public IActionResult Search(string cust_id, string project_id)
{}

也就是这里的 cust_id 和 project_id 既多是正常字符,也多是 Unicode 编码。ide

编码的问题很好解决,在网上找了一段正则替换的:this

public static string Unicode2String(this string source)
{
    return new Regex(@"%u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
                         source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
}

用的时候调一下就能够了。编码

public IActionResult Search(string cust_id, string project_id)
{
    cust_id = cust_id.Unicode2String();
    project_id = project_id.Unicode2String();
    //....
}

可是后来发现,这样的地方不少,若是每一个Action 都加这个东西,有点 Low 。天然就想到了用模型绑定器解决这个问题,就像
咱们总用的 FromBody FromQuery 等等。记得之前用过 ModelBinder ,翻了翻之前的代码,写了一个类:spa

    public class UnicodeModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(string))
                return Task.CompletedTask;
            var mn = bindingContext.FieldName;
            string result;
            if (bindingContext.ActionContext.HttpContext.Request.Query.ContainsKey(mn))
                result = bindingContext.ActionContext.HttpContext.Request.Query[mn];
            else
                result = null;
            if(result != null)
            {
                result = result.Unicode2String();
                bindingContext.Result = ModelBindingResult.Success(result);
            }
            return Task.CompletedTask;
        }
    }

功能很简单,就是判断是否是 string ,若是是 判断 Request.Query 是有没有,若是有,就用上面的方法转一下。
而后在 Action 上这样改:代理

public IActionResult Search([ModelBinder(BinderType = typeof(UnicodeModelBinder))]string cust_id,[ModelBinder(BinderType = typeof(UnicodeModelBinder))] string project_id)
{
    //删掉这句 cust_id = cust_id.Unicode2String();
    //删掉这句 project_id = project_id.Unicode2String();
    //....
}

问题解决了,可是这样有点丑,加的这个东西太长了。而后就想能不能直接定义一个 ModelBinder 这样的东西。
先来看看 ModelBinder 怎么写的。code

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
    public class ModelBinderAttribute : Attribute, IBinderTypeProviderMetadata, IBindingSourceMetadata, IModelNameProvider
    {
        public ModelBinderAttribute();
        public ModelBinderAttribute(Type binderType);
        public Type BinderType { get; set; }
        public virtual BindingSource BindingSource { get; protected set; }
        public string Name { get; set; }
    }

那么写一个子类行不行?试试吧。
写了一个类 UnicodeAttribute 继承 ModelBinder,而后指定 BinderType = typeof(UnicodeModelBinder)。
结果发现不行,由于 BinderType 不是 virtual 的,无法 override 。
既然继承不行,那试试代理模式吧。写个代理模式的类,把 ModelBinder 代理一下,代码以下:blog

    public class UnicodeAttribute : Attribute, IBinderTypeProviderMetadata, IBindingSourceMetadata, IModelNameProvider
    {
        private readonly ModelBinderAttribute modelBinderAttribute = new ModelBinderAttribute() { BinderType = typeof(UnicodeModelBinder) };

        public BindingSource BindingSource => modelBinderAttribute.BindingSource;

        public string Name => modelBinderAttribute.Name;

        public Type BinderType => modelBinderAttribute.BinderType;
    }

而后Action 改为这样:继承

public IActionResult Search([Unicode]string cust_id,[Unicode] string project_id)
{
    //....
}

跑起来看一下,完美解决。

相关文章
相关标签/搜索