处理解密数据的数据类型 - 作为方法参数数据类型

时间:2016-07-10 18:25:23

标签: c# encryption

在我们的几个AJAX端点上,我们接受一个字符串并立即在方法中,我们尝试将字符串解密为int。好像很多重复的代码。

public void DoSomething(string myId)
{
  int? id = DecryptId(myId);
}

其中DecryptId是常用方法(在基本控制器类中)

我想创建一个为我做这一切的类,并使用这个新类作为方法参数中的数据类型(而不是string),然后使用返回解密的getter int?

最好的方法是什么?

修改

这是我的实施工作。

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; }
}

1 个答案:

答案 0 :(得分:1)

这是我的实施工作。

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());