2

I'm trying to write a custom model binder that can bind a property decorated with an attribute to a differently-named request property e.g.

JSON request

{
    "app": "acme"
}

Request model (excerpt)

[Alias("app")]
public string ApplicationName { get; set; }

... should result in ApplicationName being populated with the value 'acme'. I'm getting stuck writing the custom model binder for this:

Model binder

public BindToAliasModelBinder : IModelBinder {
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
        ...
    }
}

Model binder provider

public class BindFromAliasModelBinderProvider : ModelBinderProvider {
    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType) {
        return new BindFromAliasModelBinder();
    }
}

I've registered the provider globally and the binder is being hit as expected. I'm at a loss for what to do next - how do I iterate through the request values and conditionally bind based on the presence of the attribute?

1 Answer 1

1

If all you want to do is aliasing, you can use JsonPropertyAttribute, something like [JsonProperty(PropertyName = "app")] on the property.

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried this, unfortunately it doesn't appear to work for binding. I've also the DataMember attribute with no luck.
Did you ever find a solution. I wast to use short names in the actual json but have meaningful variable name for debugging

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.