Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added type converter support via TypeConverter<T> #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/MinimalApiPlayground/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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> uri) =>
$"The redirect uri = {uri}")
.WithTags("Examples");

// Overriding/mutating response defaults using middleware
app.UseMutateResponse();

Expand Down
47 changes: 47 additions & 0 deletions src/MinimalApiPlayground/Properties/TypeConverterOfT.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System.ComponentModel;

namespace Microsoft.AspNetCore.Http;

/// <summary>
/// A custom binder that uses <see cref="TypeConverter"/>s to convert from a <see cref="string"/> to the target <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The that providers a TypeConverter implementation</typeparam>
public readonly struct TypeConverter<TValue>
{
// Cache the type coverter instance for this generic type
private static readonly TypeConverter s_converter = TypeDescriptor.GetConverter(typeof(TValue));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this s_ abomination?


public TValue Value { get; }

public TypeConverter(TValue value)
{
Value = value;
}

public static implicit operator TValue(TypeConverter<TValue> value) => value.Value;

public override string ToString()
{
return Value!.ToString()!;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did the compiler need the nullable escape here?

}

public static bool TryParse(string s, out TypeConverter<TValue> 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;
}
}