本文整理汇总了C#中Microsoft.AspNet.Mvc.ModelBinding.EmptyModelMetadataProvider.GetMetadataForType方法的典型用法代码示例。如果您正苦于以下问题:C# EmptyModelMetadataProvider.GetMetadataForType方法的具体用法?C# EmptyModelMetadataProvider.GetMetadataForType怎么用?C# EmptyModelMetadataProvider.GetMetadataForType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.AspNet.Mvc.ModelBinding.EmptyModelMetadataProvider
的用法示例。
在下文中一共展示了EmptyModelMetadataProvider.GetMetadataForType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: JsonPatchInputFormatter_ReadsMultipleOperations_Successfully
public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully()
{
// Arrange
var formatter = new JsonPatchInputFormatter();
var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}," +
"{\"op\": \"remove\", \"path\" : \"Customer/Name\"}]";
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(JsonPatchDocument<Customer>));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata);
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.False(result.HasError);
var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(result.Model);
Assert.Equal("add", patchDoc.Operations[0].op);
Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
Assert.Equal("John", patchDoc.Operations[0].value);
Assert.Equal("remove", patchDoc.Operations[1].op);
Assert.Equal("Customer/Name", patchDoc.Operations[1].path);
}
示例2: GetBindingContext
private static ModelBindingContext GetBindingContext(Type modelType)
{
var metadataProvider = new EmptyModelMetadataProvider();
ModelBindingContext bindingContext = new ModelBindingContext
{
ModelMetadata = metadataProvider.GetMetadataForType(modelType),
ModelName = "someName",
OperationBindingContext = new OperationBindingContext
{
HttpContext = new DefaultHttpContext(),
MetadataProvider = metadataProvider,
}
};
bindingContext.OperationBindingContext.HttpContext.Request.Method = "GET";
return bindingContext;
}
示例3: CanRead_ReturnsTrueForAnySupportedContentType
public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
{
// Arrange
var formatter = new JsonInputFormatter();
var contentBytes = Encoding.UTF8.GetBytes("content");
var httpContext = GetHttpContext(contentBytes, contentType: requestContentType);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(string));
var formatterContext = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: new ModelStateDictionary(),
metadata: metadata);
// Act
var result = formatter.CanRead(formatterContext);
// Assert
Assert.Equal(expectedCanRead, result);
}
示例4: MultipartFormatter_CanRead_ReturnsTrueForSupportedMediaTypes
public void MultipartFormatter_CanRead_ReturnsTrueForSupportedMediaTypes(string requestContentType)
{
// Arrange
var formatter = new MultipartFormatter();
var httpContext = new DefaultHttpContext();
httpContext.Request.ContentType = requestContentType;
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(void));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: new ModelStateDictionary(),
metadata: metadata);
// Act
var result = formatter.CanRead(context);
// Assert
Assert.True(result);
}
示例5: ReadAsync_AddsModelValidationErrorsToModelState
public async Task ReadAsync_AddsModelValidationErrorsToModelState()
{
// Arrange
var content = "{name: 'Person Name', Age: 'not-an-age'}";
var formatter = new JsonInputFormatter();
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(User));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata);
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.True(result.HasError);
Assert.Equal(
"Could not convert string to decimal: not-an-age. Path 'Age', line 1, position 39.",
modelState["Age"].Errors[0].Exception.Message);
}
示例6: JsonFormatterReadsComplexTypes
public async Task JsonFormatterReadsComplexTypes()
{
// Arrange
var content = "{name: 'Person Name', Age: '30'}";
var formatter = new JsonInputFormatter();
var contentBytes = Encoding.UTF8.GetBytes(content);
var httpContext = GetHttpContext(contentBytes);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(User));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: new ModelStateDictionary(),
metadata: metadata);
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.False(result.HasError);
var userModel = Assert.IsType<User>(result.Model);
Assert.Equal("Person Name", userModel.Name);
Assert.Equal(30, userModel.Age);
}
示例7: ModelSetter_SetNullableNonNull_UpdatesModelExplorer
public void ModelSetter_SetNullableNonNull_UpdatesModelExplorer()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var metadata = metadataProvider.GetMetadataForType(typeof(bool?));
var explorer = new ModelExplorer(metadataProvider, metadata, model: null);
var viewData = new ViewDataDictionary(metadataProvider)
{
ModelExplorer = explorer,
};
// Act
viewData.Model = true;
// Assert
Assert.NotNull(viewData.ModelMetadata);
Assert.NotNull(viewData.ModelExplorer);
Assert.Same(metadata, viewData.ModelMetadata);
Assert.Same(metadata.ModelType, explorer.ModelType);
Assert.NotSame(explorer, viewData.ModelExplorer);
Assert.Equal(viewData.Model, viewData.ModelExplorer.Model);
var model = Assert.IsType<bool>(viewData.Model);
Assert.True(model);
}
示例8: ReadAsync_UsesContentTypeCharSet_ToReadStream
public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream()
{
// Arrange
var expectedException = TestPlatformHelper.IsMono ? typeof(SerializationException) :
typeof(XmlException);
var expectedMessage = TestPlatformHelper.IsMono ?
"Expected element 'TestLevelTwo' in namespace '', but found Element node 'DummyClass' in namespace ''" :
"The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";
var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>1000</SampleInt></DummyClass>");
var formatter = new XmlDataContractSerializerInputFormatter();
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16");
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(TestLevelOne));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata,
readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);
// Act
var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));
Assert.Equal(expectedMessage, ex.Message);
}
示例9: AddMultipleErrors
// Adds errors for various parts of the model, including the root.
private void AddMultipleErrors(ModelStateDictionary modelState)
{
modelState.AddModelError("Property3.Property2", "This is an error for Property3.Property2.");
modelState.AddModelError("Property3.OrderedProperty3", "This is an error for Property3.OrderedProperty3.");
modelState.AddModelError("Property3.OrderedProperty2", "This is an error for Property3.OrderedProperty2.");
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForProperty(typeof(ValidationModel), nameof(ValidationModel.Property3));
modelState.AddModelError("Property3", "This is an error for Property3.");
modelState.AddModelError("Property3", new InvalidCastException("Exception will be ignored."), metadata);
metadata = provider.GetMetadataForProperty(typeof(ValidationModel), nameof(ValidationModel.Property2));
modelState.AddModelError("Property2", "This is an error for Property2.");
modelState.AddModelError("Property2", "This is another error for Property2.");
modelState.AddModelError("Property2", new OverflowException("Produces invalid value message"), metadata);
metadata = provider.GetMetadataForType(typeof(ValidationModel));
modelState.AddModelError(string.Empty, "This is an error for the model root.");
modelState.AddModelError(string.Empty, "This is another error for the model root.");
modelState.AddModelError(string.Empty, new InvalidOperationException("Another ignored Exception."), metadata);
}
示例10: ReadAsync_UsesTryAddModelValidationErrorsToModelState
public async Task ReadAsync_UsesTryAddModelValidationErrorsToModelState()
{
// Arrange
var content = "{name: 'Person Name', Age: 'not-an-age'}";
var formatter = new JsonInputFormatter();
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(User));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata);
modelState.MaxAllowedErrors = 3;
modelState.AddModelError("key1", "error1");
modelState.AddModelError("key2", "error2");
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.True(result.HasError);
Assert.False(modelState.ContainsKey("age"));
var error = Assert.Single(modelState[""].Errors);
Assert.IsType<TooManyModelErrorsException>(error.Exception);
}
示例11: ReadAsync_UsesContentTypeCharSet_ToReadStream
public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream()
{
// Arrange
var expectedException = TestPlatformHelper.IsMono ? typeof(InvalidOperationException) :
typeof(XmlException);
var expectedMessage = TestPlatformHelper.IsMono ?
"There is an error in XML document." :
"The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";
var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>1000</SampleInt></DummyClass>");
var formatter = new XmlSerializerInputFormatter();
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16");
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(TestLevelOne));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata);
// Act and Assert
var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));
Assert.Equal(expectedMessage, ex.Message);
}
示例12: CanRead_ReturnsTrueOnlyForJsonPatchContentType
public void CanRead_ReturnsTrueOnlyForJsonPatchContentType(string requestContentType, bool expectedCanRead)
{
// Arrange
var formatter = new JsonPatchInputFormatter();
var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}]";
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes, contentType: requestContentType);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(JsonPatchDocument<Customer>));
var formatterContext = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata);
// Act
var result = formatter.CanRead(formatterContext);
// Assert
Assert.Equal(expectedCanRead, result);
}
示例13: JsonPatchInputFormatter_ReturnsModelStateErrors_InvalidModelType
public async Task JsonPatchInputFormatter_ReturnsModelStateErrors_InvalidModelType()
{
// Arrange
var exceptionMessage = "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type " +
$"'{typeof(Customer).FullName}' because the type requires a JSON object ";
var formatter = new JsonPatchInputFormatter();
var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}]";
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes, contentType: "application/json-patch+json");
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(Customer));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata);
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.True(result.HasError);
Assert.Contains(exceptionMessage, modelState[""].Errors[0].Exception.Message);
}
示例14: CanRead_ReturnsFalse_NonJsonPatchContentType
public void CanRead_ReturnsFalse_NonJsonPatchContentType(Type modelType)
{
// Arrange
var formatter = new JsonPatchInputFormatter();
var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}]";
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes, contentType: "application/json-patch+json");
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(modelType);
var formatterContext = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata);
// Act
var result = formatter.CanRead(formatterContext);
// Assert
Assert.False(result);
}
示例15: GetActionArguments_AddsActionArgumentsToModelStateDictionary_IfBinderReturnsTrue
public async Task GetActionArguments_AddsActionArgumentsToModelStateDictionary_IfBinderReturnsTrue()
{
// Arrange
Func<object, int> method = x => 1;
var actionDescriptor = new ReflectedActionDescriptor
{
MethodInfo = method.Method,
Parameters = new List<ParameterDescriptor>
{
new ParameterDescriptor
{
Name = "foo",
ParameterBindingInfo = new ParameterBindingInfo("foo", typeof(object))
}
}
};
var value = "Hello world";
var binder = new Mock<IModelBinder>();
var metadataProvider = new EmptyModelMetadataProvider();
binder.Setup(b => b.BindModelAsync(It.IsAny<ModelBindingContext>()))
.Callback((ModelBindingContext context) =>
{
context.ModelMetadata = metadataProvider.GetMetadataForType(modelAccessor: null,
modelType: typeof(string));
context.Model = value;
})
.Returns(Task.FromResult(result: true));
var actionContext = new ActionContext(new RouteContext(Mock.Of<HttpContext>()),
actionDescriptor);
var bindingContext = new ActionBindingContext(actionContext,
Mock.Of<IModelMetadataProvider>(),
binder.Object,
Mock.Of<IValueProvider>(),
Mock.Of<IInputFormatterProvider>(),
Enumerable.Empty<IModelValidatorProvider>());
var actionBindingContextProvider = new Mock<IActionBindingContextProvider>();
actionBindingContextProvider.Setup(p => p.GetActionBindingContextAsync(It.IsAny<ActionContext>()))
.Returns(Task.FromResult(bindingContext));
var invoker = new ReflectedActionInvoker(actionContext,
actionDescriptor,
Mock.Of<IControllerFactory>(),
actionBindingContextProvider.Object,
Mock.Of<INestedProviderManager<FilterProviderContext>>());
var modelStateDictionary = new ModelStateDictionary();
// Act
var result = await invoker.GetActionArguments(modelStateDictionary);
// Assert
Assert.Equal(1, result.Count);
Assert.Equal(value, result["foo"]);
}