Popular Posts

July 11, 2024

How to implement custom model binding in ASP.NET Core

 

Custom model binding in ASP.NET Core allows you to control how data from HTTP requests is bound to action method parameters. This is useful when you need to handle complex data types, manipulate incoming data before binding, or support custom formats.

Here’s how to implement custom model binding in ASP.NET Core:

1. Create a Custom Model Binder

To create a custom model binder, you need to implement the IModelBinder interface. The interface has a single method BindModelAsync, which contains the logic to bind the model.

Example: Custom Model Binder for a Complex Type

public class CustomModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var modelName = bindingContext.ModelName;

        // Attempt to fetch the value from the value providers
        var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

        if (valueProviderResult == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);

        var value = valueProviderResult.FirstValue;

        // Implement your custom binding logic here
        // For example, convert a comma-separated string to a list of integers

        if (string.IsNullOrEmpty(value))
        {
            return Task.CompletedTask;
        }

        var values = value.Split(',').Select(int.Parse).ToList();

        bindingContext.Result = ModelBindingResult.Success(values);
        return Task.CompletedTask;
    }
}
How to implement custom model binding in ASP.NET Core


2. Create a Custom Model Binder Provider

Next, create a model binder provider to specify when your custom model binder should be used. Implement the IModelBinderProvider interface.

Example: Custom Model Binder Provider

public class CustomModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (context.Metadata.ModelType == typeof(List<int>))
        {
            return new CustomModelBinder();
        }

        return null;
    }
}

3. Register the Custom Model Binder Provider

Register your custom model binder provider in the Startup.cs file.

Example:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =>
    {
        options.ModelBinderProviders.Insert(0, new CustomModelBinderProvider());
    });
}

4. Use the Custom Model Binder

You can now use the custom model binder in your controller actions. When the model binder encounters the specified type (e.g., List<int>), it will use your custom model binder.

Example: Controller Action

[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
    [HttpGet]
    public IActionResult Get([ModelBinder(BinderType = typeof(CustomModelBinder))] List<int> ids)
    {
        return Ok(ids);
    }
}

Custom Model Binder with Attributes

Sometimes, you might want to use attributes to specify the custom model binder.

Example: Custom Model Binder Attribute

public class CustomModelBinderAttribute : Attribute, IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (context.Metadata.ModelType == typeof(List<int>))
        {
            return new CustomModelBinder();
        }

        return null;
    }
}

Usage:

[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
    [HttpGet]
    public IActionResult Get([CustomModelBinder] List<int> ids)
    {
        return Ok(ids);
    }
}

Summary

Custom model binding in ASP.NET Core involves creating a custom model binder, a model binder provider, and registering the provider in your application. This approach allows you to handle complex data types, custom formats, and manipulate incoming data before binding it to action method parameters. By implementing these steps, you can create flexible and robust solutions for handling data in ASP.NET Core applications.


No comments:
Write comments