我有一个简单的 Web API 服务。大约有 10 种不同的 GET 操作,这些操作根据输入参数返回各种数据库记录的 JSON 输出。
对于一个特定端点,一个空格,“ ”应该是一个有效的参数,但它被转换为 null。有没有解决的办法?
例如网址是:http://localhost:1234/DataAccess/RetrieveProductData?parameterOne=null¶meterTwo=574&problemParameter=%20¶meterThree=AB12
在控制器操作中我可以看到以下内容:
int? parameterOne => null
string parameterTwo => "574"
string problemParameter => null
string parameterThree => "AB12"
有什么方法可以真正获得:
string problemParameter => " "
或者这是不可能的?
我通过添加一个解决了这个问题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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)