本文整理汇总了C#中Nancy.ModelBinding.BindingContext类的典型用法代码示例。如果您正苦于以下问题:C# BindingContext类的具体用法?C# BindingContext怎么用?C# BindingContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BindingContext类属于Nancy.ModelBinding命名空间,在下文中一共展示了BindingContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Deserialize
/// <summary>
/// Deserialize the request body to a model
/// </summary>
/// <param name="contentType">Content type to deserialize</param><param name="bodyStream">Request body stream</param><param name="context">Current <see cref="T:Nancy.ModelBinding.BindingContext"/>.</param>
/// <returns>
/// Model instance
/// </returns>
public object Deserialize(string contentType, Stream bodyStream, BindingContext context)
{
object deserializedObject;
using (var inputStream = new StreamReader(bodyStream))
{
// deserialize json
deserializedObject = JSON.Deserialize(inputStream, context.DestinationType, Options);
// .. then, due to NancyFx's support for blacklisted properties, we need to get the propertyInfo first (read from cache if possible)
var comparisonType = GetTypeForBlacklistComparison(context.DestinationType);
BindingMemberInfo[] bindingMemberInfo;
if (CachedBindingMemberInfo.TryGetValue(comparisonType, out bindingMemberInfo) == false)
{
bindingMemberInfo = comparisonType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => new BindingMemberInfo(p)).ToArray();
// the following is somewhat dirty but oh well
SpinWait.SpinUntil(() => CachedBindingMemberInfo.ContainsKey(comparisonType) || CachedBindingMemberInfo.TryAdd(comparisonType, bindingMemberInfo));
}
// ... and then compare whether there's anything blacklisted
if (bindingMemberInfo.Except(context.ValidModelBindingMembers).Any())
{
// .. if so, take object and basically eradicated value(s) for the blacklisted properties.
// this is inspired by https://raw.githubusercontent.com/NancyFx/Nancy.Serialization.JsonNet/master/src/Nancy.Serialization.JsonNet/JsonNetBodyDeserializer.cs
// but again.. only *inspired*.
// The main difference is, that the instance Jil returned from the JSON.Deserialize() call will be wiped clean, no second/new instance will be created.
return CleanBlacklistedMembers(context, deserializedObject, bindingMemberInfo);
}
return deserializedObject;
}
}
示例2: when_deserializing
public void when_deserializing()
{
// Given
JsonConvert.DefaultSettings = JsonApiSerializerFixture.GetJsonSerializerSettings;
var guid = Guid.NewGuid();
string source = string.Format("{{\"someString\":\"some string value\",\"someGuid\":\"{0}\"}}", guid);
var context = new BindingContext
{
DestinationType = typeof (TestData),
ValidModelBindingMembers = typeof (TestData).GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => new BindingMemberInfo(p)),
};
// When
object actual;
using (var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(source)))
{
IBodyDeserializer sut = new JsonApiBodyDeserializer();
actual = sut.Deserialize("application/vnd.api+json", bodyStream, context);
}
// Then
var actualData = Assert.IsType<TestData>(actual);
Assert.Equal("some string value", actualData.SomeString);
Assert.Equal(guid, actualData.SomeGuid);
}
示例3: when_deserializing_with_blacklisted_property
public void when_deserializing_with_blacklisted_property()
{
// Given
var guid = Guid.NewGuid();
string source = string.Format("{{\"SomeString\":\"some string value\",\"SomeGuid\":\"{0}\"}}", guid);
var context = new BindingContext
{
DestinationType = typeof(TestData),
ValidModelBindingMembers = typeof(TestData).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(propertyInfo => propertyInfo.Name != "SomeString").Select(p => new BindingMemberInfo(p))
};
// When
object actual;
using (var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(source)))
{
IBodyDeserializer jilBodyDeserializer = new JilBodyDeserializer();
actual = jilBodyDeserializer.Deserialize("application/json", bodyStream, context);
}
// Then
Assert.IsInstanceOfType(actual, typeof(TestData));
var actualData = actual as TestData;
Assert.IsNotNull(actualData);
Assert.IsNull(actualData.SomeString);
Assert.AreEqual(guid, actualData.SomeGuid);
}
示例4: when_binding_to_a_collection_with_blacklisted_property
public void when_binding_to_a_collection_with_blacklisted_property()
{
// Given
var guid = Guid.NewGuid();
string source = string.Format("{{\"SomeString\":\"some string value\",\"SomeGuid\":\"{0}\"}}", guid);
var context = new BindingContext
{
DestinationType = typeof(Stuff),
ValidModelBindingMembers = typeof(Stuff).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(propertyInfo => propertyInfo.Name != "SomeString").Select(p => new BindingMemberInfo(p)),
};
// Given
var module = new ConfigurableNancyModule(c => c.Post("/stuff", (_, m) =>
{
var stuff = m.Bind<List<Stuff>>("SomeString");
return stuff.ToJSON();
}));
var bootstrapper = new TestBootstrapper(config => config.Module(module));
// When
var browser = new Browser(bootstrapper);
var result = browser.Post("/stuff", with =>
{
with.HttpRequest();
with.JsonBody(new List<Stuff> { new Stuff(1, "one"), new Stuff(2, "two") }, new JilSerializer());
});
// Then
Assert.AreEqual("[{\"Id\":1,\"SomeString\":null},{\"Id\":2,\"SomeString\":null}]", result.Body.AsString());
}
示例5: CreateCollectionInstance
private object CreateCollectionInstance(BindingContext context, List<object> items)
{
Type destinationType = context.DestinationType;
if (destinationType.IsList())
{
IList list = (IList)Activator.CreateInstance(destinationType);
foreach (var item in items)
list.Add(item);
return list;
}
if (destinationType.IsArray)
{
var array = Array.CreateInstance(destinationType.GetElementType(), items.Count);
for (int i = 0; i < items.Count; i++)
array.SetValue(items[i], i);
return array;
}
return null;
}
示例6: Deserialize
/// <summary>
/// Deserialize the request body to a model
/// </summary>
/// <param name="mediaRange">Content type to deserialize</param>
/// <param name="bodyStream">Request body stream</param>
/// <param name="context">Current context</param>
/// <returns>Model instance</returns>
public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context)
{
if (bodyStream.CanSeek)
{
bodyStream.Position = 0;
}
var deserializedObject =
this.serializer.Deserialize(new StreamReader(bodyStream), context.DestinationType);
var properties =
context.DestinationType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => new BindingMemberInfo(p));
var fields =
context.DestinationType.GetFields(BindingFlags.Public | BindingFlags.Instance)
.Select(f => new BindingMemberInfo(f));
if (properties.Concat(fields).Except(context.ValidModelBindingMembers).Any())
{
return CreateObjectWithBlacklistExcluded(context, deserializedObject);
}
return deserializedObject;
}
示例7: Deserialize
public object Deserialize(string contentType, System.IO.Stream bodyStream, BindingContext context)
{
object result = null;
try
{
var settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.Converters.Add(new StringEnumConverter());
settings.Converters.Add (new IsoDateTimeConverter()
{
DateTimeStyles = System.Globalization.DateTimeStyles.AssumeLocal
});
var serializer = JsonSerializer.Create(settings);
bodyStream.Position = 0;
string bodyText;
using (var bodyReader = new StreamReader(bodyStream))
{
bodyText = bodyReader.ReadToEnd();
}
result = serializer.Deserialize(new StringReader(bodyText), context.DestinationType);
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
return result;
}
示例8: when_deserializing_while_the_body_stream_was_not_at_position_zero
public void when_deserializing_while_the_body_stream_was_not_at_position_zero()
{
// Repro of https://github.com/NancyFx/Nancy.Serialization.JsonNet/issues/22
// Given
JsonConvert.DefaultSettings = JsonNetSerializerFixture.GetJsonSerializerSettings;
var guid = Guid.NewGuid();
string source = string.Format("{{\"someString\":\"some string value\",\"someGuid\":\"{0}\"}}", guid);
var context = new BindingContext
{
DestinationType = typeof(TestData),
ValidModelBindingMembers = typeof(TestData).GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => new BindingMemberInfo(p)),
};
// When
object actual;
using (var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(source)))
{
IBodyDeserializer sut = new JsonNetBodyDeserializer();
bodyStream.Position = 1;
actual = sut.Deserialize("application/json", bodyStream, context);
}
// Then
var actualData = Assert.IsType<TestData>(actual);
Assert.Equal("some string value", actualData.SomeString);
Assert.Equal(guid, actualData.SomeGuid);
}
示例9: CollectionConverterFixture
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Object"/> class.
/// </summary>
public CollectionConverterFixture()
{
this.converter = new CollectionConverter();
this.context = new BindingContext() { TypeConverters = new[] { new FallbackConverter() } };
this.mockStringTypeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => mockStringTypeConverter.CanConvertTo(null, null)).WithAnyArguments().Returns(true);
A.CallTo(() => mockStringTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(string.Empty);
}
示例10: Collection_type_conversion_should_use_type_converter
public void Collection_type_conversion_should_use_type_converter()
{
const string input = "one,two,three";
var mockContext = new BindingContext() { TypeConverters = new[] { this.mockStringTypeConverter } };
converter.Convert(input, typeof(List<string>), mockContext);
A.CallTo(() => this.mockStringTypeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Times(3));
}
示例11: Deserialize
/// <summary>
/// Deserialize the request body to a model
/// </summary>
/// <param name="contentType">Content type to deserialize</param>
/// <param name="bodyStream">Request body stream</param>
/// <param name="context">Current context</param>
/// <returns>Model instance</returns>
public object Deserialize(string contentType, Stream bodyStream, BindingContext context)
{
var deserializedObject = JsonSerializer.DeserializeFromStream(context.DestinationType, bodyStream);
if (context.DestinationType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Except(context.ValidModelProperties).Any())
{
return this.CreateObjectWithBlacklistExcluded(context, deserializedObject);
}
return deserializedObject;
}
开发者ID:rasmus-beck,项目名称:Nancy.Serialization.ServiceStack,代码行数:18,代码来源:ServiceStackBodyDeserializer.cs
示例12: CreateObjectWithBlacklistExcluded
private object CreateObjectWithBlacklistExcluded(BindingContext context, object deserializedObject)
{
var returnObject = Activator.CreateInstance(context.DestinationType);
foreach (var property in context.ValidModelProperties)
{
this.CopyPropertyValue(property, deserializedObject, returnObject);
}
return returnObject;
}
开发者ID:rasmus-beck,项目名称:Nancy.Serialization.ServiceStack,代码行数:11,代码来源:ServiceStackBodyDeserializer.cs
示例13: BuildInstance
private object BuildInstance(BindingContext context, string[] lines)
{
if (lines.Length > 1)
{
string[] fieldNames = lines[0].Split(',');
string[] fieldValues = lines[1].Split(',');
return CreateInstance(fieldNames, fieldValues, context.DestinationType, context);
}
return null;
}
示例14: ConvertCollection
private static object ConvertCollection(object items, Type destinationType, BindingContext context)
{
var returnCollection = Activator.CreateInstance(destinationType);
var collectionAddMethod =
destinationType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
foreach (var item in (IEnumerable)items)
{
collectionAddMethod.Invoke(returnCollection, new[] { item });
}
return returnCollection;
}
示例15: CanDeserialize
public bool CanDeserialize(string contentType, BindingContext context)
{
if (String.IsNullOrEmpty(contentType))
{
return false;
}
var contentMimeType = contentType.Split(';')[0];
return contentMimeType.Equals("application/csv", StringComparison.InvariantCultureIgnoreCase) ||
contentMimeType.Equals("text/csv", StringComparison.InvariantCultureIgnoreCase) ||
(contentMimeType.StartsWith("application/vnd", StringComparison.InvariantCultureIgnoreCase) &&
contentMimeType.EndsWith("+csv", StringComparison.InvariantCultureIgnoreCase));
}