Web API form-urlencoded binding to different property names

后端 未结 2 548
半阙折子戏
半阙折子戏 2020-12-11 04:04

I am expecting a POST request with content type set to:

Content-Type: application/x-www-form-urlencoded

Request body looks like

相关标签:
2条回答
  • 2020-12-11 04:30

    It's an old post but maybe this could helps other people. Here is a solution with an AliasAttribute and the associated ModelBinder

    It could be used like this :

    [ModelBinder(typeof(AliasBinder))]
    public class MyModel
    {
        [Alias("state")]
        public string Status { get; set; }
    }
    

    Don't hesitate to comment my code :)

    Every Idea / comment is welcome.

    0 讨论(0)
  • 2020-12-11 04:38

    I'm 98% certain (I looked the source code) that WebAPI doesn't support it.

    If you really need to support different property names, you can either:

    1. Add additional properties to the Actor class which serves as alias.

    2. Create your own model binder.

    Here is a simple model binder:

    public sealed class ActorDtoModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var actor = new Actor();
    
            var firstNameValueResult = bindingContext.ValueProvider.GetValue(CreateFullPropertyName(bindingContext, "First_Name"));
            if(firstNameValueResult != null) {
                actor.FirstName = firstNameValueResult.AttemptedValue;
            }
    
            var lastNameValueResult = bindingContext.ValueProvider.GetValue(CreateFullPropertyName(bindingContext, "Last_Name"));
            if(lastNameValueResult != null) {
                actor.LastName = lastNameValueResult.AttemptedValue;
            }
    
            bindingContext.Model = actor;
    
            bindingContext.ValidationNode.ValidateAllProperties = true;
    
            return true;
        }
    
        private string CreateFullPropertyName(ModelBindingContext bindingContext, string propertyName)
        {
            if(string.IsNullOrEmpty(bindingContext.ModelName))
            {
                return propertyName;
            }
            return bindingContext.ModelName + "." + propertyName;
        }
    }
    

    If you are up for the challenge, you can try to create a generic model binder.

    0 讨论(0)
提交回复
热议问题