Web Services Web API空白参数值正在转换为空值

zmeyuzjn  于 2022-11-15  发布在  其他
关注(0)|答案(2)|浏览(157)

我有一个简单的Web API服务,大约有10个不同的GET操作,这些操作根据输入参数返回各种数据库记录的JSON输出。
对于一个特定的终结点,单个空格"“应该是有效的参数,但它将被转换为null。是否有解决此问题的方法?
例如,URL为:http://localhost:1234/DataAccess/RetrieveProductData?parameterOne=null&parameterTwo=574&problemParameter=%20&parameterThree=AB12
在控制器内我可以看到以下动作:

int? parameterOne => null
string parameterTwo => "574"
string problemParameter => null
string parameterThree => "AB12"

有没有办法实际得到:

string problemParameter => " "

还是这不可能?

x4shl7ld

x4shl7ld1#

我通过添加一个ParameterBindingRule解决了这个问题,该ParameterBindingRule具有足够的条件来匹配我遇到问题的确切参数:
注册码:

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;
}
4zcjmb1e

4zcjmb1e2#

您应该在客户端应用程序中执行此操作。是否要在Android上反序列化它?

相关问题