Skip to content
This repository was archived by the owner on Nov 20, 2018. It is now read-only.

Commit 6893517

Browse files
committed
Harden the PathString converter
1 parent a3c5a19 commit 6893517

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

src/Microsoft.AspNetCore.Http.Abstractions/PathString.cs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -459,9 +459,20 @@ public static implicit operator string(PathString path)
459459

460460
internal class PathStringConverter : TypeConverter
461461
{
462+
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
463+
=> sourceType == typeof(string)
464+
? true
465+
: base.CanConvertFrom(context, sourceType);
466+
462467
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
463-
{
464-
return new PathString((string)value);
465-
}
468+
=> value is string
469+
? new PathString((string)value)
470+
: base.ConvertFrom(context, culture, value);
471+
472+
public override object ConvertTo(ITypeDescriptorContext context,
473+
CultureInfo culture, object value, Type destinationType)
474+
=> destinationType == typeof(string)
475+
? value.ToString()
476+
: base.ConvertTo(context, culture, value, destinationType);
466477
}
467478
}

test/Microsoft.AspNetCore.Http.Abstractions.Tests/PathStringTests.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,11 +208,18 @@ public void ToUriComponentEscapeCorrectly(string category, string input, string
208208
}
209209

210210
[Fact]
211-
public void PathStringConvertsFromString()
211+
public void PathStringConvertsOnlyToAndFromString()
212212
{
213213
var converter = TypeDescriptor.GetConverter(typeof(PathString));
214214
PathString result = (PathString)converter.ConvertFromInvariantString("/foo");
215215
Assert.Equal("/foo", result.ToString());
216+
Assert.Equal("/foo", converter.ConvertTo(result, typeof(string)));
217+
Assert.True(converter.CanConvertFrom(typeof(string)));
218+
Assert.False(converter.CanConvertFrom(typeof(int)));
219+
Assert.False(converter.CanConvertFrom(typeof(bool)));
220+
Assert.True(converter.CanConvertTo(typeof(string)));
221+
Assert.False(converter.CanConvertTo(typeof(int)));
222+
Assert.False(converter.CanConvertTo(typeof(bool)));
216223
}
217224
}
218225
}

0 commit comments

Comments
 (0)