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

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

其中 DecryptId 是常用方法(在基本 Controller 类中)

我想创建一个为我完成所有这些工作的类,并使用这个新类作为方法参数中的数据类型(而不是 string ),然后是一个返回解密的 getterint?
做到这一点的最佳方法是什么?

编辑:

这是我正在运行的实现。
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());

关于c# - 处理解密数据的数据类型 - 作为方法参数数据类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38295152/

10-12 04:02
查看更多