在我们的几个
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());