c# – 处理解密数据的数据类型 – 作为方法参数数据类型
发布时间:2020-12-15 22:33:41 所属栏目:百科 来源:网络整理
导读:在我们的几个 AJAX端点上,我们接受一个字符串并立即在方法中,我们尝试将字符串解密为int.好像很多重复的代码. public void DoSomething(string myId){ int? id = DecryptId(myId);} 其中DecryptId是一种常见方法(在基本控制器类中) 我想创建一个为我做这一切
在我们的几个
AJAX端点上,我们接受一个字符串并立即在方法中,我们尝试将字符串解密为int.好像很多重复的代码.
public void DoSomething(string myId) { int? id = DecryptId(myId); } 其中DecryptId是一种常见方法(在基本控制器类中) 我想创建一个为我做这一切的类,并使用这个新类作为方法参数中的数据类型(而不是字符串),然后使用返回解密的int的getter? 最好的方法是什么? 编辑: 这是我的实施工作. public class EncryptedInt { public int? Id { get; set; } } public class EncryptedIntModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException("bindingContext"); } var rawVal = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var ei = new EncryptedInt { Id = Crypto.DecryptToInt(rawVal.AttemptedValue) }; return ei; } } public class EncryptedIntAttribute : CustomModelBinderAttribute { private readonly IModelBinder _binder; public EncryptedIntAttribute() { _binder = new EncryptedIntModelBinder(); } public override IModelBinder GetBinder() { return _binder; } } 解决方法
这是我的实施工作.
public class EncryptedInt { public int? Id { get; set; } // User-defined conversion from EncryptedInt to int public static implicit operator int(EncryptedInt d) { return d.Id; } } public class EncryptedIntModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException("bindingContext"); } var rawVal = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var ei = new EncryptedInt { Id = Crypto.DecryptToInt(rawVal.AttemptedValue) }; return ei; } } public class EncryptedIntAttribute : CustomModelBinderAttribute { private readonly IModelBinder _binder; public EncryptedIntAttribute() { _binder = new EncryptedIntModelBinder(); } public override IModelBinder GetBinder() { return _binder; } } …以及Application_Start方法中的Global.asax.cs(如果您希望它对所有EncryptedInt类型都是全局的,而不是在每个引用上使用Attribute)… // register Model Binder for EncryptedInt type ModelBinders.Binders.Add(typeof(EncryptedInt),new EncryptedIntModelBinder()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |