1

I want a customize modelbinder for .net core mvc action parameters, but I not sure DefaultModelBinder is available in .net core. this is .net standard example for customize modelbinder.

public class EncryptDataBinder : DefaultModelBinder
        {
            public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                object result = 0;
                if (bindingContext.ModelType == typeof(int))
                {
                    var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                    if (valueProviderResult != null)
                    {
                     // decryption code                    
                    }
                }
            return base.BindModel(controllerContext, bindingContext);
           }   
    }
0

1 Answer 1

1

In ASP.NET Core, you need implements IModelBinder.

A simple demo below about custom model binder to change the bound Id:

Model

public class Author
{
    [ModelBinder(BinderType = typeof(EncryptDataBinder))]
    public int Id { get; set; }
    public string Name { get; set; }
}

Custom IModelBinder

public class EncryptDataBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }
        
        if (bindingContext.ModelType == typeof(int))
        {
            // Try to fetch the value of the argument by name
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult != null)
            {
                int id = 3;
                //bind the new id....
                bindingContext.Result = ModelBindingResult.Success(id);
                return Task.CompletedTask;
            }
        }             
        return Task.CompletedTask;
    }
}

Controller:

[HttpPost]
public IActionResult Post([FromForm]Author model)
{
    return Ok(model);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.