简体   繁体   中英

How to get data frombody in a custom ModelBinder?

I'm creating a custom implementation of IModelBinder in a .NET Core 1.1 (full framework) app.

I have a class ActivityModel that has an interface property:

public class ActivityModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Type { get; set; }
    public IActivityContent Content { get; set; }    // marker interface  
    //more unimportant props
}

The idea is that the client can send this object with a Content property that can be one of many (currently 8, but it may be growing) different classes.

This way we can have one endpoint in the API (for each CRUD operation) that can handle all of these different types of objects.

I'm in the process of implementing a ModelBinder to turn the object sent from the client into a concrete class, and here's what I've got so far:

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }
        var content = bindingContext.ValueProvider.GetValue("content");

        return TaskCache.CompletedTask;
    }

I'm currently just trying to get the Content object into a variable so I can work with it more, but ValueProvider only has RouteValueProvider and QueryStringValueProvider. How do I get the body data in here?

You can use controller context with FormValueProvider in custom model binder and implement the code like following.

public Task BindModelAsync(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    if (bindingContext == null)
    {
        throw new ArgumentNullException(nameof(bindingContext));
    }

    bindingContext.ValueProvider = new FormValueProvider(controllerContext);
    ActivityModel model = (ActivityModel)bindingContext.Model ?? new ActivityModel();
    model.content = bindingContext.ValueProvider.GetValue("Content")

    return TaskCache.CompletedTask;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM