Created
May 15, 2017 18:47
-
-
Save ArtemAvramenko/6a47e0d9948541003786d893888fd154 to your computer and use it in GitHub Desktop.
Interpret query string 'null' as null for specified properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 FromUriNullableAttribute : ModelBinderAttribute | |
{ | |
private readonly string[] _nullableColumns; | |
public FromUriNullableAttribute(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) | |
{ } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment