the whitespace parameter value on the web api is now being converted to null

I resolved this issue by adding a ParameterBindingRule with sufficient criteria to match on the exact parameter I had an issue with:

Register code:

config.ParameterBindingRules.Add(p =>
            {
                // Override rule only for string and get methods, Otherwise let Web API do what it is doing
                // By default if the argument is only whitespace, it will be set to null. This fixes that
                // commissionOption column default value is a single space ' '.
                // Therefore a valid input parameter here is a ' '. By default this is converted to null. This overrides default behaviour.
                if (p.ParameterType == typeof(string) && p.ActionDescriptor.SupportedHttpMethods.Contains(HttpMethod.Get) && p.ParameterName == "commissionOption")
                {
                    return new StringParameterBinding(p);
                }

                return null;
            });

StringParameterBinding.cs:

public StringParameterBinding(HttpParameterDescriptor parameter)
    : base(parameter)
{
}

public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
    var value = actionContext.Request.GetQueryNameValuePairs().Where(f => f.Key == this.Descriptor.ParameterName).Select(s => s.Value).FirstOrDefault();

    // By default if the argument is only whitespace, it will be set to null. This fixes that
    actionContext.ActionArguments[this.Descriptor.ParameterName] = value;

    var tsc = new TaskCompletionSource<object>();
    tsc.SetResult(null);
    return tsc.Task;
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top