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

Bind byte array from base64 config value #43150

Merged
merged 4 commits into from
Oct 15, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,23 @@ private static bool TryConvertValue(Type type, string value, string path, out ob
return true;
}

if (type == typeof(byte[]))
{
if (value is null)
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved
{
return true;
}
try
{
result = Convert.FromBase64String(value);
}
catch (FormatException ex)
{
error = new InvalidOperationException(SR.Format(SR.Error_FailedBinding, path, type), ex);
}
return true;
}

return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ public struct ValueTypeOptions
public string MyString { get; set; }
}

public class ByteArrayOptions
{
public byte[] MyByteArray { get; set; }
}

[Fact]
public void CanBindIConfigurationSection()
{
Expand Down Expand Up @@ -812,6 +817,40 @@ public void CanBindValueTypeOptions()
Assert.Equal("hello world", options.MyString);
}

[Fact]
public void CanBindByteArray()
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved
{
var bytes = new byte[] { 1, 2, 3, 4 };
var dic = new Dictionary<string, string>
{
{ "MyByteArray", Convert.ToBase64String(bytes) }
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(dic);
var config = configurationBuilder.Build();

var options = config.Get<ByteArrayOptions>();
Assert.Equal(bytes, options.MyByteArray);
}

[Fact]
public void ExceptionWhenTryingToBindToByteArray()
safern marked this conversation as resolved.
Show resolved Hide resolved
{
var dic = new Dictionary<string, string>
{
{ "MyByteArray", "(not a valid base64 string)" }
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(dic);
var config = configurationBuilder.Build();

var exception = Assert.Throws<InvalidOperationException>(
() => config.Get<ByteArrayOptions>());
Assert.Equal(
safern marked this conversation as resolved.
Show resolved Hide resolved
SR.Format(SR.Error_FailedBinding, "MyByteArray", typeof(byte[])),
exception.Message);
}

private interface ISomeInterface
{
}
Expand Down