derek lawless
derek lawless

Reputation: 2564

ASP.NET Web API binding model properties to different request properties

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?

Upvotes: 2

Views: 637

Answers (1)

RaghuRam Nadiminti
RaghuRam Nadiminti

Reputation: 6793

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

Upvotes: 1

Related Questions