简体   繁体   中英

web api action parameter convert empty string parameter to null

I have a some web Api actions with a lot of string parameter. for some of these parameters , client sends empty string instead of null but I need to save null in database in case of empty string. I tried with model binder and JSONconvertor but failed.

FYI; I need a generic solution as I don't want check parameter inside the method body and replace them with null.

You can use the DisplayFormat attribute on your string properties to automatically convert empty strings to null.

[DisplayFormat(ConvertEmptyStringToNull = true)]
public string MyString { get; set; }

Thanks Sarathy , your solution may also work but I ended with following solution: 1)Creating custom model binder like following

 public class EmptyStringModelBinder : System.Web.Mvc.IModelBinder
    {
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            string key = bindingContext.ModelName;
            ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
            if (val != null)
            {
                var s = val.AttemptedValue as string;
                if (s != null && (s.IsEmpty() || s.Trim().IsEmpty()))
                {
                    return null;
                }

                return val.AttemptedValue;
            }

            return null;
        }
    }

2)Mark action method parameter with ModelBinder attribute

public ActionResult UpdateAttribute(int id, 
                                     int AttributeTypeId,
                                     int? Number_Value, 
                                     decimal? Money_Value,
                                            [ModelBinder(typeof(EmptyStringModelBinder))]string Text_Value)

or you could add this model binder at configuration. it will inspect all string parameters and replace empty string with null(maybe not desired)

If you use the [Required] attribute on the string property, but make it nullable in the database, WebApi will convert the empty string it receives in the Json to a null value.

My requirement was for the opposite. I have a non-nullable field in the database, and wanted to save the empty string to the database. For this requirement, I had to remove the [Required] attribute and add [DisplayFormat(ConvertEmptyStringToNull = false)]

Then the empty strings in the JSON were persisted to the database.

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