From 4dceef73de99984cd679a9011d538931ec17c066 Mon Sep 17 00:00:00 2001 From: David Fowler Date: Fri, 17 Sep 2021 20:19:03 -0700 Subject: [PATCH] Added type converter support via TypeConverter --- src/MinimalApiPlayground/Program.cs | 6 +++ .../Properties/TypeConverterOfT.cs | 47 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 src/MinimalApiPlayground/Properties/TypeConverterOfT.cs diff --git a/src/MinimalApiPlayground/Program.cs b/src/MinimalApiPlayground/Program.cs index 0af9e78..01c7269 100644 --- a/src/MinimalApiPlayground/Program.cs +++ b/src/MinimalApiPlayground/Program.cs @@ -148,6 +148,12 @@ $"model: {paging.Model}, valid: {paging.ModelState.IsValid}") .WithTags("Examples"); +// Using type converters this will bind the redirect_uri query string parameter +// to a Uri object. +app.MapGet("/redirect", ([FromQuery(Name = "redirect_uri")] TypeConverter uri) => + $"The redirect uri = {uri}") + .WithTags("Examples"); + // Overriding/mutating response defaults using middleware app.UseMutateResponse(); diff --git a/src/MinimalApiPlayground/Properties/TypeConverterOfT.cs b/src/MinimalApiPlayground/Properties/TypeConverterOfT.cs new file mode 100644 index 0000000..b0df606 --- /dev/null +++ b/src/MinimalApiPlayground/Properties/TypeConverterOfT.cs @@ -0,0 +1,47 @@ +using System.ComponentModel; + +namespace Microsoft.AspNetCore.Http; + +/// +/// A custom binder that uses s to convert from a to the target . +/// +/// The that providers a TypeConverter implementation +public readonly struct TypeConverter +{ + // Cache the type coverter instance for this generic type + private static readonly TypeConverter s_converter = TypeDescriptor.GetConverter(typeof(TValue)); + + public TValue Value { get; } + + public TypeConverter(TValue value) + { + Value = value; + } + + public static implicit operator TValue(TypeConverter value) => value.Value; + + public override string ToString() + { + return Value!.ToString()!; + } + + public static bool TryParse(string s, out TypeConverter result) + { + if (s_converter is null || !s_converter.CanConvertFrom(typeof(string))) + { + result = default; + return false; + } + + var value = (TValue?)s_converter.ConvertFromInvariantString(s); + + if (value is null) + { + result = default; + return false; + } + + result = new(value); + return true; + } +} \ No newline at end of file