Skip to content

Commit d0cc04f

Browse files
authored
Convert InvalidOperationException to InvalidDataException for form reader (#20138)
1 parent cfac5ed commit d0cc04f

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

src/Http/WebUtilities/src/FormPipeReader.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -377,10 +377,17 @@ private string GetDecodedString(ReadOnlySpan<byte> readOnlySpan)
377377
// We will also create a string from it by the end of the function.
378378
var span = MemoryMarshal.CreateSpan(ref Unsafe.AsRef(readOnlySpan[0]), readOnlySpan.Length);
379379

380-
var bytes = UrlDecoder.DecodeInPlace(span, isFormEncoding: true);
381-
span = span.Slice(0, bytes);
380+
try
381+
{
382+
var bytes = UrlDecoder.DecodeInPlace(span, isFormEncoding: true);
383+
span = span.Slice(0, bytes);
382384

383-
return _encoding.GetString(span);
385+
return _encoding.GetString(span);
386+
}
387+
catch (InvalidOperationException ex)
388+
{
389+
throw new InvalidDataException("The form value contains invalid characters.", ex);
390+
}
384391
}
385392
else
386393
{

src/Http/WebUtilities/test/FormPipeReaderTests.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,18 @@ public async Task ReadFormAsync_EmptyValueWithoutEqualsWithAdditionalEntryAllowe
7878
Assert.Equal("2", formCollection["baz"].ToString());
7979
}
8080

81+
[Fact]
82+
public async Task ReadFormAsync_ValueContainsInvalidCharacters_Throw()
83+
{
84+
var bodyPipe = await MakePipeReader("%00");
85+
86+
var exception = await Assert.ThrowsAsync<InvalidDataException>(
87+
() => ReadFormAsync(new FormPipeReader(bodyPipe)));
88+
89+
Assert.Equal("The form value contains invalid characters.", exception.Message);
90+
Assert.IsType<InvalidOperationException>(exception.InnerException);
91+
}
92+
8193
[Fact]
8294
public async Task ReadFormAsync_ValueCountLimitMet_Success()
8395
{

src/Shared/UrlDecoder/UrlDecoder.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ private static int UnescapePercentEncoding(ref int scan, Span<byte> buffer, bool
294294
/// Read the next char and convert it into hexadecimal value.
295295
///
296296
/// The <paramref name="scan"/> index will be moved to the next
297-
/// byte no matter no matter whether the operation successes.
297+
/// byte no matter whether the operation successes.
298298
/// </summary>
299299
/// <param name="scan">The index of the byte in the buffer to read</param>
300300
/// <param name="buffer">The byte span from which the hex to be read</param>

0 commit comments

Comments
 (0)