The data type for processing decrypted data - as the data type of the method parameter

At several of our AJAX endpoints, we accept a string and immediately in the method, we try to decrypt the string into int. There seems to be a lot of duplicate code.

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

Where DecryptId is the general method (in the base controller class)

I would like to create a class that does all this for me, and use this new class as the data type in the method argument (instead string), and then getterthat returns the decrypted oneint?

What is the best way to do this?

Edit:

Here is my work that works.

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; }
}
+4
source share
1 answer

Here is my implementation.

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

... Global.asax.cs Application_Start ( , EncryptedInt )...

// register Model Binder for EncryptedInt type
ModelBinders.Binders.Add(typeof(EncryptedInt), new EncryptedIntModelBinder());
+1

All Articles