微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 处理解密数据的数据类型 – 作为方法参数数据类型

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐