public async Task BindModelAsync_LogsFormatterRejectionAndSelection() { // Arrange var sink = new TestSink(); var loggerFactory = new TestLoggerFactory(sink, enabled: true); var inputFormatters = new List <IInputFormatter>() { new TestInputFormatter(canRead: false), new TestInputFormatter(canRead: true), }; var provider = new TestModelMetadataProvider(); provider.ForType <Person>().BindingDetails(d => d.BindingSource = BindingSource.Body); var bindingContext = GetBindingContext(typeof(Person), metadataProvider: provider); bindingContext.HttpContext.Request.ContentType = "application/json"; var binder = new BodyModelBinder(inputFormatters, new TestHttpRequestStreamReaderFactory(), loggerFactory); // Act await binder.BindModelAsync(bindingContext); var writeList = sink.Writes.ToList(); // Assert Assert.Equal($"Attempting to bind model of type '{typeof(Person)}' using the name 'someName' in request data ...", writeList[0].State.ToString()); Assert.Equal($"Rejected input formatter '{typeof(TestInputFormatter)}' for content type 'application/json'.", writeList[1].State.ToString()); Assert.Equal($"Selected input formatter '{typeof(TestInputFormatter)}' for content type 'application/json'.", writeList[2].State.ToString()); }
public NewtonsoftJsonModelBinder( IHttpRequestStreamReaderFactory readerFactory, ILoggerFactory loggerFactory, IOptions <MvcOptions> optionsProvider, IOptions <MvcNewtonsoftJsonOptions> newtonsoftOptionsProvider, ArrayPool <char> charPool, ObjectPoolProvider objectPoolProvider) { var options = optionsProvider.Value; var formatters = options.InputFormatters.ToList(); var jsonFormatter = formatters.OfType <SystemTextJsonInputFormatter>().FirstOrDefault(); var newtonsoftJsonFormatter = formatters.OfType <NewtonsoftJsonInputFormatter>().FirstOrDefault(); if (jsonFormatter != null && newtonsoftJsonFormatter == null) { var jsonFormatterIndex = formatters.IndexOf(jsonFormatter); var logger = loggerFactory.CreateLogger <NewtonsoftJsonInputFormatter>(); var settings = JsonSerializerSettingsProvider.CreateSerializerSettings(); formatters[jsonFormatterIndex] = new NewtonsoftJsonInputFormatter( logger, settings, charPool, objectPoolProvider, options, newtonsoftOptionsProvider.Value); } _bodyBinder = new BodyModelBinder(formatters, readerFactory, loggerFactory, options); }
public MyModelBinder(IHttpRequestStreamReaderFactory readerFactory, ILoggerFactory loggerFactory, IOptions <MvcOptions> options, IOptions <MvcJsonOptions> jsonOptions, ArrayPool <char> charPool, ObjectPoolProvider objectPoolProvider) { var formatters = options.Value.InputFormatters.ToList(); int jsonFormatterIndex = formatters.FirstIndexOf(formatter => formatter is JsonInputFormatter); JsonSerializerSettings myCustomSettings = ... formatters[jsonFormatterIndex] = new JsonInputFormatter(loggerFactory.CreateLogger("MyCustomJsonFormatter"), myCustomSettings, charPool, objectPoolProvider, options.Value, jsonOptions.Value); _bodyModelBinder = new BodyModelBinder(formatters, readerFactory, loggerFactory, options.Value); }
/// <inheritdoc cref="BindModelAsync"/> public Task BindModelAsync(ModelBindingContext bindingContext) { if (!bindingContext.HttpContext.WebSockets.IsWebSocketRequest) { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult != ValueProviderResult.None) { bindingContext.Result = ModelBindingResult.Success(valueProviderResult.FirstValue); return(Task.CompletedTask); } // 바인딩 소스가 HTTP+Body 인 경우 if (bindingContext.BindingSource == BindingSource.Body) { var binder = new BodyModelBinder(_options.InputFormatters, _requestStreamReaderFactory, _loggerFactory, _options); return(binder.BindModelAsync(bindingContext)); } } else { if (string.IsNullOrWhiteSpace(bindingContext.ModelName)) { if (!(bindingContext.HttpContext.Items["web-socket-io-packet"] is WebSocketIoPacket packet)) { return(Task.CompletedTask); } try { var obj = JsonConvert.DeserializeObject(packet.Data.ToString(), bindingContext.ModelType); bindingContext.Result = ModelBindingResult.Success(obj); } catch { return(Task.CompletedTask); } } else { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult == ValueProviderResult.None) { return(Task.CompletedTask); } bindingContext.Result = ModelBindingResult.Success(valueProviderResult.FirstValue); } } return(Task.CompletedTask); }
/// <summary> /// 获取Binder /// </summary> /// <param name="context"></param> /// <returns></returns> public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context.BindingInfo.BindingSource != null && context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Body)) { var readerFactory = context.Services.GetService <IHttpRequestStreamReaderFactory>(); var loggerFactory = context.Services.GetService <ILoggerFactory>(); var bodyModelBinder = new BodyModelBinder(this.mvcOptions.InputFormatters, readerFactory, loggerFactory, this.mvcOptions); return(new StringPropertyTrimModelBinder(bodyModelBinder, this.propertyFilter)); } return(null); }
public async Task BindModelAsync_DoesNotThrowNullReferenceException() { // Arrange var httpContext = new DefaultHttpContext(); var provider = new TestModelMetadataProvider(); provider.ForType <Person>().BindingDetails(d => d.BindingSource = BindingSource.Body); var bindingContext = GetBindingContext( typeof(Person), httpContext: httpContext, metadataProvider: provider); var binder = new BodyModelBinder(new List <IInputFormatter>(), new TestHttpRequestStreamReaderFactory()); // Act & Assert (does not throw) await binder.BindModelAsync(bindingContext); }
public async Task BindModelAsync_LogsNoFormatterSelectedAndRemoveFromBodyAttribute() { // Arrange var sink = new TestSink(); var loggerFactory = new TestLoggerFactory(sink, enabled: true); var inputFormatters = new List <IInputFormatter>() { new TestInputFormatter(canRead: false), new TestInputFormatter(canRead: false), }; var provider = new TestModelMetadataProvider(); provider.ForType <Person>().BindingDetails(d => d.BindingSource = BindingSource.Body); var bindingContext = GetBindingContext(typeof(Person), metadataProvider: provider); bindingContext.HttpContext.Request.ContentType = "multipart/form-data"; bindingContext.BinderModelName = bindingContext.ModelName; var binder = new BodyModelBinder(inputFormatters, new TestHttpRequestStreamReaderFactory(), loggerFactory); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.Collection( sink.Writes, write => Assert.Equal( $"Attempting to bind model of type '{typeof(Person)}' using the name 'someName' in request data ...", write.State.ToString()), write => Assert.Equal( $"Rejected input formatter '{typeof(TestInputFormatter)}' for content type 'multipart/form-data'.", write.State.ToString()), write => Assert.Equal( $"Rejected input formatter '{typeof(TestInputFormatter)}' for content type 'multipart/form-data'.", write.State.ToString()), write => Assert.Equal( "No input formatter was found to support the content type 'multipart/form-data' for use with the [FromBody] attribute.", write.State.ToString()), write => Assert.Equal( $"To use model binding, remove the [FromBody] attribute from the property or parameter named '{bindingContext.ModelName}' with model type '{bindingContext.ModelType}'.", write.State.ToString()), write => Assert.Equal( $"Done attempting to bind model of type '{typeof(Person)}' using the name 'someName'.", write.State.ToString())); }
/// <summary>Initializes a new instance of the <see cref="IdentityModelBinder{TKey}"/> class.</summary> /// <param name="formatters">Registered input formatters for mvc pipeline.</param> /// <param name="readerFactory">Stream reader factory instance.</param> protected IdentityModelBinder(IList <IInputFormatter> formatters, IHttpRequestStreamReaderFactory readerFactory) { _defaultBinder = new BodyModelBinder(formatters, readerFactory); }
public FormBodyStringTrimModelBinder(IList <IInputFormatter> formatters, IHttpRequestStreamReaderFactory readerFactory) { bodyModelBinder = new BodyModelBinder(formatters, readerFactory); }
// [Fact] // public void RetrieveModelFromJsonSuccessfully_UsingBodyModelBinder() // { // // Arrange // var mockHttpContext = new Mock<HttpContext>(); // string plainPostData = "{\"draw\":1,\"columns\":[{\"data\":\"name\",\"name\":\"name\",\"searchable\":true,\"orderable\":true,\"search\":{\"value\":\"\",\"regex\":false}},{\"data\":\"parentName\",\"name\":\"parentName\",\"searchable\":true,\"orderable\":true,\"search\":{\"value\":\"\",\"regex\":false}},{\"data\":\"\",\"name\":\"\",\"searchable\":false,\"orderable\":false,\"search\":{\"value\":\"\",\"regex\":false}}],\"order\":[{\"column\":0,\"dir\":\"asc\"}],\"start\":0,\"length\":25,\"search\":{\"value\":\"\",\"regex\":false}}"; // byte[] postData = Encoding.UTF8.GetBytes(plainPostData); // mockHttpContext.Setup(x => x.Request.Body).Returns(new MemoryStream(postData)); // mockHttpContext.Setup(x => x.Request.ContentType).Returns("application/json"); // var bindingContext = CreateBindingContext(typeof(DataTableParamViewModel), mockHttpContext.Object); // IList<IInputFormatter> formatters = new List<IInputFormatter>() // { // new JsonInputFormatter(NullLogger.Instance, new JsonSerializerSettings(), ArrayPool<char>.Shared, new DefaultObjectPoolProvider()) // }; // var binder = CreateBinder(formatters); // // Act // binder.BindModelAsync(bindingContext); // // Assert // Assert.True(bindingContext.Result.IsModelSet); // Assert.NotNull(bindingContext.Result.Model); // } private static BodyModelBinder CreateBinder(IList <IInputFormatter> formatters) { var binder = new BodyModelBinder(formatters, new TestHttpRequestStreamReaderFactory()); return(binder); }
public NtBodyModelBinder(IList <IInputFormatter> formatters, IHttpRequestStreamReaderFactory readerFactory) // : base(formatters, readerFactory) { defaultBinder = new BodyModelBinder(formatters, readerFactory); }
/// <summary> /// String属性trim处理的模型绑定者 /// </summary> /// <param name="bodyModelBinder"></param> /// <param name="propertyFilter"></param> public StringPropertyTrimModelBinder(BodyModelBinder bodyModelBinder, Func <PropertyInfo, bool> propertyFilter) { this.bodyModelBinder = bodyModelBinder; this.stringPropertyCache = new StringPropertyCache(propertyFilter); }