我有一个 Web API 方法:
public List<Task> GetTasks([FromUri] TaskFilter filter)
{
}
该方法具有带有可空标识符列表的参数:
public class TaskFilter
{
public IList<int?> Assignees { get; set; }
}
当我调用它时:
GET /tasks?assignees=null
服务器返回错误:
{
"message":"The request is invalid.",
"modelState": {
"assignees": [ "The value 'null' is not valid for Nullable`1." ]
}
}
只有当我传递空字符串时它才有效:
GET /tasks?assignees=
但是标准查询字符串转换器(来自 JQuery、Angular 等)不能以这种方式处理空值。
如何让ASP.NET能够解释
'null'
如null
?更新:查询字符串可以包含多个标识符,例如:
GET /tasks?assignees=1&assignees=2&assignees=null
更新2: JQuery 将数组中的 null 转换为空字符串,ASP.NET 将它们解释为 null。所以问题是关于从 Angular 1.6 (
$HttpParamSerializerProvider
) 调用 WebAPI更新3:我知道解决方法,但我不要求它们。我想要针对特定问题的解决方案:
null
值 List<int?>
因为 API 文档是自动生成的,我不想将文本数组视为参数类型 JQuery.param
以这种方式工作)null
数组项到空字符串 最佳答案
最后,我找到了使用自定义值提供者的解决方案:
using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ValueProviders;
using System.Web.Http.ValueProviders.Providers;
using System.Globalization;
using System.Net.Http;
using System.Web.Http.ModelBinding;
public sealed class NullableValueProviderAttribute : ModelBinderAttribute
{
private readonly string[] _nullableColumns;
public NullableValueProviderAttribute(params string[] nullableColumns)
{
_nullableColumns = nullableColumns;
}
public override IEnumerable<ValueProviderFactory> GetValueProviderFactories(HttpConfiguration configuration)
{
return new ValueProviderFactory[] { new NullableValueProviderFactory(_nullableColumns) };
}
}
public class NullableValueProviderFactory : ValueProviderFactory, IUriValueProviderFactory
{
private readonly string[] _nullableColumns;
public NullableValueProviderFactory(string[] nullableColumns)
{
_nullableColumns = nullableColumns;
}
public override IValueProvider GetValueProvider(HttpActionContext actionContext)
{
return new NullableQueryStringValueProvider(actionContext, CultureInfo.InvariantCulture, _nullableColumns);
}
}
public class NullableQueryStringValueProvider : NameValuePairsValueProvider
{
private static readonly string[] _nullValues = new string[] { "null", "undefined" };
private static IEnumerable<KeyValuePair<string, string>> GetQueryNameValuePairs(HttpRequestMessage request, string[] nullableColumns)
{
foreach (var pair in request.GetQueryNameValuePairs())
{
var isNull = Array.IndexOf(nullableColumns, pair.Key) >= 0 && Array.IndexOf(_nullValues, pair.Value) >= 0;
yield return isNull ? new KeyValuePair<string, string>(pair.Key, "") : pair;
};
}
public NullableQueryStringValueProvider(HttpActionContext actionContext, CultureInfo culture, string[] nullableColumns) :
base(GetQueryNameValuePairs(actionContext.ControllerContext.Request, nullableColumns), culture)
{ }
}
并在 Web API 操作中指定它:
public List<Task> GetTasks([NullableValueProvider("assignees")] TaskFilter filter)
{
}
关于asp.net - 如何使 ASP.NET 停止将 null 解释为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43784044/