private void Bind(string methodName) { //创建FormatterParameterBinding对象 MethodInfo method = typeof(ContactsController).GetMethod(methodName); HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(this.ControllerContext.ControllerDescriptor, method); HttpParameterDescriptor parameterDescriptor = actionDescriptor.GetParameters().First(); MediaTypeFormatter[] formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }; FormatterParameterBinding parameterBinding = new FormatterParameterBinding(parameterDescriptor, formatters, null); //创建HttpActionBinding并执行 HttpActionBinding actionBinding = new HttpActionBinding(actionDescriptor,new FormatterParameterBinding[] { parameterBinding }); HttpActionContext actionContext =new HttpActionContext(this.ControllerContext, actionDescriptor); try { actionBinding.ExecuteBindingAsync(actionContext, CancellationToken.None).Wait(); //获取绑定参数对象并打印相关数据 Contact contact = (Contact)actionContext.ActionArguments["contact"]; Console.WriteLine("{0,-12}: {1}", "Name", contact.Name); Console.WriteLine("{0,-12}: {1}", "Phone No.", contact.PhoneNo); Console.WriteLine("{0,-12}: {1}", "EmailAddress", contact.EmailAddress); Console.WriteLine("{0,-12}: {1}", "Address", contact.Address); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void ExecuteBindingAsync_Traces_And_Invokes_Inner_ReadAsync() { // Arrange Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true }; mockParamDescriptor.Setup(d => d.ParameterName).Returns("paramName"); mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof (string)); FormatterParameterBinding binding = new FormatterParameterBinding(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null); TestTraceWriter traceWriter = new TestTraceWriter(); FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(binding, traceWriter); HttpActionContext actionContext = ContextUtil.CreateActionContext(); actionContext.Request.Content = new StringContent("true"); actionContext.Request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider(); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteBindingAsync" }, new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ExecuteBindingAsync" } }; // Act Task task = tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None); task.Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Equal("True", actionContext.ActionArguments["paramName"]); }
public async Task ReadContentAsync_PassesCancellationToken_Further() { // Arrange var parameter = new Mock <HttpParameterDescriptor>(); parameter.Setup(p => p.IsOptional).Returns(false); IBodyModelValidator validator = null; HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("app/test"); IFormatterLogger logger = null; CancellationTokenSource cts = new CancellationTokenSource(); Mock <MediaTypeFormatter> formatter = new Mock <MediaTypeFormatter>(); formatter.Setup(f => f.CanReadType(typeof(int))).Returns(true); formatter.Object.SupportedMediaTypes.Add(request.Content.Headers.ContentType); formatter.Setup(f => f.ReadFromStreamAsync(typeof(int), It.IsAny <Stream>(), request.Content, logger, cts.Token)) .Returns(Task.FromResult <object>(42)) .Verifiable(); var formatters = new[] { formatter.Object }; FormatterParameterBinding binding = new FormatterParameterBinding(parameter.Object, formatters, validator); // Act await binding.ReadContentAsync(request, typeof(int), formatters, logger, cts.Token); // Assert formatter.Verify(); }
public void ReadContentAsync_Throws_ForNoContentType() { var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost"); request.Content = new StringContent("The quick, brown fox tripped and fell."); request.Content.Headers.ContentType = null; var formatters = new MediaTypeFormatterCollection(); var descriptor = new Mock <HttpParameterDescriptor>(); descriptor.Setup(desc => desc.IsOptional).Returns(false); var binding = new FormatterParameterBinding(descriptor.Object, formatters, null); HttpResponseException exception = Assert.Throws <HttpResponseException>( () => binding.ReadContentAsync(request, typeof(string), formatters, null) ); Assert.Equal(HttpStatusCode.UnsupportedMediaType, exception.Response.StatusCode); HttpError error; exception.Response.TryGetContentValue(out error); Assert.Equal( "The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.", error.Message ); }
public FormatterParameterBindingTracer(FormatterParameterBinding innerBinding, ITraceWriter traceWriter) : base(innerBinding.Descriptor, innerBinding.Formatters, innerBinding.BodyModelValidator) { Contract.Assert(innerBinding != null); Contract.Assert(traceWriter != null); _innerBinding = innerBinding; _traceWriter = traceWriter; }
public void ReadContentAsync_Throws_ForUnsupportedMediaType() { var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost"); request.Content = new StringContent("The quick, brown fox tripped and fell."); var formatters = new MediaTypeFormatterCollection(); var descriptor = new Mock<HttpParameterDescriptor>(); descriptor.Setup(desc => desc.IsOptional).Returns(false); var binding = new FormatterParameterBinding(descriptor.Object, formatters, null); HttpResponseException exception = Assert.Throws<HttpResponseException>( () => binding.ReadContentAsync(request, typeof(string), formatters, null)); Assert.Equal(HttpStatusCode.UnsupportedMediaType, exception.Response.StatusCode); HttpError error; exception.Response.TryGetContentValue(out error); Assert.Equal( "The request entity's media type 'text/plain' is not supported for this resource.", error.Message); }
public void ReadContentAsync_PassesCancellationToken_Further() { // Arrange var parameter = new Mock<HttpParameterDescriptor>(); parameter.Setup(p => p.IsOptional).Returns(false); IBodyModelValidator validator = null; HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("app/test"); IFormatterLogger logger = null; CancellationTokenSource cts = new CancellationTokenSource(); Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>(); formatter.Setup(f => f.CanReadType(typeof(int))).Returns(true); formatter.Object.SupportedMediaTypes.Add(request.Content.Headers.ContentType); formatter.Setup(f => f.ReadFromStreamAsync(typeof(int), It.IsAny<Stream>(), request.Content, logger, cts.Token)) .Returns(Task.FromResult<object>(42)) .Verifiable(); var formatters = new[] { formatter.Object }; FormatterParameterBinding binding = new FormatterParameterBinding(parameter.Object, formatters, validator); // Act binding.ReadContentAsync(request, typeof(int), formatters, logger, cts.Token).Wait(); // Assert formatter.Verify(); }
public FormatterParameterBindingTracer(FormatterParameterBinding innerBinding, ITraceWriter traceWriter) : base(innerBinding.Descriptor, innerBinding.Formatters, innerBinding.BodyModelValidator) { _innerBinding = innerBinding; _traceWriter = traceWriter; }
public void Decorator_GetInner_On_FormatterParameterBindingTracer_Returns_FormatterParameterBinding() { // Arrange HttpParameterDescriptor httpParameterDescriptor = new Mock<HttpParameterDescriptor>().Object; MediaTypeFormatterCollection mediaTypeFormatterCollection = new MediaTypeFormatterCollection(); FormatterParameterBinding expectedInner = new FormatterParameterBinding(httpParameterDescriptor, mediaTypeFormatterCollection, null); FormatterParameterBindingTracer productUnderTest = new FormatterParameterBindingTracer(expectedInner, new TestTraceWriter()); // Act FormatterParameterBinding actualInner = Decorator.GetInner(productUnderTest as FormatterParameterBinding); // Assert Assert.Same(expectedInner, actualInner); }