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 WrapperResolvesAuthenticationFilterFromDependencyScope() { var builder = new ContainerBuilder(); builder.Register<ILogger>(c => new Logger()).InstancePerDependency(); var activationCount = 0; builder.Register<IAutofacAuthenticationFilter>(c => new TestAuthenticationFilter(c.Resolve<ILogger>())) .AsWebApiAuthenticationFilterFor<TestController>(c => c.Get()) .InstancePerRequest() .OnActivated(e => activationCount++); var container = builder.Build(); var resolver = new AutofacWebApiDependencyResolver(container); var configuration = new HttpConfiguration { DependencyResolver = resolver }; var requestMessage = new HttpRequestMessage(); requestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, configuration); var contollerContext = new HttpControllerContext { Request = requestMessage }; var controllerDescriptor = new HttpControllerDescriptor { ControllerType = typeof(TestController) }; var methodInfo = typeof(TestController).GetMethod("Get"); var actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo); var actionContext = new HttpActionContext(contollerContext, actionDescriptor); var context = new HttpAuthenticationContext(actionContext, Thread.CurrentPrincipal); var metadata = new FilterMetadata { ControllerType = typeof(TestController), FilterScope = FilterScope.Action, MethodInfo = methodInfo }; var wrapper = new AuthenticationFilterWrapper(metadata); wrapper.OnAuthenticate(context); Assert.That(activationCount, Is.EqualTo(1)); }
public void IsDefined_Retruns_True_WhenParameterAttributeIsFound() { UsersRpcController controller = new UsersRpcController(); Action<User> addUserMethod = controller.AddUser; ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method }; ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0]; ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo); }
public void Ctor_SetsActionsDataToken() { var actions = new ReflectedHttpActionDescriptor[0]; var route = new HttpDirectRoute("route", 0, actions); Assert.Equal(actions, route.Actions); }
public void ParameterBinderAttribute_NotNull_WhenParameterAttributeIsFound() { UsersRpcController controller = new UsersRpcController(); Action<User> addUserMethod = controller.AddUser; ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method }; ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0]; ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo); Assert.NotNull(parameterDescriptor.ParameterBinderAttribute); }
public void IsOptional_Returns_True_ForOptionalParameter() { UsersRpcController controller = new UsersRpcController(); MethodInfo methodWithOptionalParam = GetType().GetMethod("MethodWithOptionalParam", BindingFlags.Static | BindingFlags.NonPublic); ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = methodWithOptionalParam }; ParameterInfo parameterInfo = methodWithOptionalParam.GetParameters()[0]; ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo); Assert.True(parameterDescriptor.IsOptional); }
public void Ctor_SetsActionsDataToken() { var actions = new ReflectedHttpActionDescriptor[0]; var route = HttpRouteBuilder.BuildDirectRoute("route", 0, actions); var actualActions = route.DataTokens[RouteKeys.ActionsDataTokenKey]; Assert.Equal(actions, actualActions); }
public void GetRouteData_AddsDefaultValuesAsNull() { var actions = new ReflectedHttpActionDescriptor[] { new ReflectedHttpActionDescriptor() }; var route = new HttpDirectRoute("movies/{id}", 0, actions); route.Defaults.Add("id", RouteParameter.Optional); var routeData = route.GetRouteData("", new HttpRequestMessage(HttpMethod.Get, "http://localhost/movies")); Assert.Null(routeData.Values["id"]); }
public void CreateBuilderWithoutResolverAndBuild_AddsDefaultValuesAsOptional() { var actions = new ReflectedHttpActionDescriptor[] { new ReflectedHttpActionDescriptor() }; var route = BuildWithoutResolver("movies/{id}", actions); route.Defaults.Add("id", RouteParameter.Optional); var routeData = route.GetRouteData("", new HttpRequestMessage(HttpMethod.Get, "http://localhost/movies")); Assert.Equal(RouteParameter.Optional, routeData.Values["id"]); }
public void GetFilters_ReturnsEmptyCollection_ForNonQueryableActions(string actionName) { HttpConfiguration config = new HttpConfiguration(); HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, "FilterProviderTest", typeof(FilterProviderTestController)); HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(FilterProviderTestController).GetMethod(actionName)); FilterInfo[] filters = new QueryFilterProvider(new EnableQueryAttribute()).GetFilters(config, actionDescriptor).ToArray(); Assert.Empty(filters); }
public void GetCustomAttributes_AttributeType_Returns_ParameterAttributes() { UsersRpcController controller = new UsersRpcController(); Action<User> addUserMethod = controller.AddUser; ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method }; ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0]; ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo); IEnumerable<FromBodyAttribute> attributes = parameterDescriptor.GetCustomAttributes<FromBodyAttribute>(); Assert.Equal(1, attributes.Count()); }
public void Default_Constructor() { ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(); Assert.Null(actionDescriptor.ActionName); Assert.Null(actionDescriptor.Configuration); Assert.Null(actionDescriptor.ControllerDescriptor); Assert.Null(actionDescriptor.MethodInfo); Assert.Null(actionDescriptor.ReturnType); Assert.NotNull(actionDescriptor.Properties); }
public void GetCustomAttributes_Returns_ParameterAttributes() { UsersRpcController controller = new UsersRpcController(); Action<User> addUserMethod = controller.AddUser; ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method }; ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0]; ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo); object[] attributes = parameterDescriptor.GetCustomAttributes<object>().ToArray(); Assert.Equal(1, attributes.Length); Assert.Equal(typeof(FromBodyAttribute), attributes[0].GetType()); }
public void GetFilters_ReturnsQueryableFilter_ForQueryableActions(string actionName) { HttpConfiguration config = new HttpConfiguration(); HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, "FilterProviderTest", typeof(FilterProviderTestController)); HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(FilterProviderTestController).GetMethod(actionName)); FilterInfo[] filters = new QueryFilterProvider(new EnableQueryAttribute()).GetFilters(config, actionDescriptor).ToArray(); Assert.Equal(1, filters.Length); Assert.Equal(FilterScope.Global, filters[0].Scope); EnableQueryAttribute filter = Assert.IsType<EnableQueryAttribute>(filters[0].Instance); }
public void LogExit_should_log_with_exit_text() { var helper = new ActionLogHelperTestDouble(_loggerMock.Object); var controllerDescriptor = new HttpControllerDescriptor { ControllerType = typeof(ActionLogHelper) }; var actionDescriptor = new ReflectedHttpActionDescriptor { ControllerDescriptor = controllerDescriptor }; helper.LogExit(actionDescriptor); Assert.AreEqual(actionDescriptor, helper.ActionDescriptorGiven); Assert.AreEqual(ActionLogHelper.ExitingText, helper.PrefixGiven); }
public void ControllerDescriptor_Property() { ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(); HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(); Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpControllerDescriptor>( instance: actionDescriptor, propertyGetter: ad => ad.ControllerDescriptor, expectedDefaultValue: null, allowNull: false, roundTripTestValue: controllerDescriptor); }
static void Main(string[] args) { HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "demo", typeof(DemoController)); MethodInfo methodInfo = typeof(DemoController).GetMethod("Get"); ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo); Console.WriteLine("{0,-16}{1,-16}{2,-16}{3,-10}", "ParameterName", "ParameterType", "DefaultValue", "IsOptional"); foreach (ReflectedHttpParameterDescriptor parameter in actionDescriptor.GetParameters()) { Console.WriteLine("{0,-16}{1,-16}{2,-16}{3,-10}", parameter.ParameterName, parameter.ParameterType.Name, parameter.DefaultValue ?? "N/A", parameter.IsOptional); } }
public void MethodInfo_Property() { ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(); Action action = new Action(() => { }); Assert.Reflection.Property<ReflectedHttpActionDescriptor, MethodInfo>( instance: actionDescriptor, propertyGetter: ad => ad.MethodInfo, expectedDefaultValue: null, allowNull: false, roundTripTestValue: action.Method); }
public void LogAction_should_log_with_format_string() { var helper = new ActionLogHelper(_loggerMock.Object); const string prefix = "pre"; var controllerDescriptor = new HttpControllerDescriptor {ControllerType = typeof (ActionLogHelper)}; var actionDescriptor = new ReflectedHttpActionDescriptor {ControllerDescriptor = controllerDescriptor}; helper.LogAction(actionDescriptor, prefix); _loggerMock.Verify(x => x.DebugFormat(ActionLogHelper.LogTextFormatString, prefix, typeof(ActionLogHelper).FullName, null)); }
public ActionResult Index() { HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor { ControllerType = typeof(FooController) }; MethodInfo methodInfo = typeof(FooController).GetMethod("Bar"); HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo) { Configuration = GlobalConfiguration.Configuration }; IActionValueBinder valueBinder = GlobalConfiguration.Configuration.Services.GetActionValueBinder(); HttpActionBinding actionBinding =valueBinder.GetBinding(actionDescriptor); return View(actionBinding.ParameterBindings); }
static void Main(string[] args) { Console.WriteLine("{0,-12}{1,-10}", "ActionName", "HttpMethod"); HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "demo", typeof(DemoController)); foreach (MethodInfo methodInfo in typeof(DemoController).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)) { ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo); foreach (HttpMethod httpMethod in actionDescriptor.SupportedHttpMethods) { Console.WriteLine("{0,-12}{1,-10}", actionDescriptor.ActionName, httpMethod); } } }
public void Parameter_Constructor() { Func<string, string, User> echoUserMethod = _controller.EchoUser; HttpConfiguration config = new HttpConfiguration(); HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, "", typeof(UsersRpcController)); ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method); Assert.Equal("EchoUser", actionDescriptor.ActionName); Assert.Equal(config, actionDescriptor.Configuration); Assert.Equal(typeof(UsersRpcController), actionDescriptor.ControllerDescriptor.ControllerType); Assert.Equal(echoUserMethod.Method, actionDescriptor.MethodInfo); Assert.Equal(typeof(User), actionDescriptor.ReturnType); Assert.NotNull(actionDescriptor.Properties); }
private static IHttpRoute BuildRoute(string routeTemplate, IInlineConstraintResolver constraintResolver = null) { ReflectedHttpActionDescriptor[] actions = new ReflectedHttpActionDescriptor[0]; // Act HttpRouteBuilder routeBuilder = new HttpRouteBuilder(constraintResolver ?? new DefaultInlineConstraintResolver()); IHttpRoute route = routeBuilder.BuildHttpRoute(routeTemplate, actions: actions); // Assertions for default, unspecified behavior: Assert.NotNull(route); Assert.Same(actions, route.DataTokens["actions"]); return route; }
public void GetEdmModelWorks(string methodName, Type entityClrType) { // Arrange HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerLowLevel", typeof(CustomerHighLevelController)); HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(CustomerHighLevelController).GetMethod(methodName)); // Act IEdmModel model = actionDescriptor.GetEdmModel(entityClrType); // Assert Assert.NotNull(model); Assert.Equal(2, model.SchemaElements.Count()); Assert.Equal(entityClrType.Name, model.SchemaElements.First().Name); Assert.Same(model, actionDescriptor.GetEdmModel(entityClrType)); }
public void Descriptions_RecognizesIgnoreApiForDirectRoutes_Controller() { var config = new HttpConfiguration(); var routeTemplate = "api/values"; var controllerDescriptor = new HttpControllerDescriptor(config, "IgnoreApiValues", typeof(IgnoreApiValuesController)); var actions = new ReflectedHttpActionDescriptor[] { new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(IgnoreApiValuesController).GetMethod("Get")), new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(IgnoreApiValuesController).GetMethod("Post")), }; config.Routes.Add("Route", new HttpDirectRoute(routeTemplate, 0, actions)); var descriptions = new ApiExplorer(config).ApiDescriptions; Assert.Empty(descriptions); }
public void Parameter_Constructor() { UsersRpcController controller = new UsersRpcController(); Func<string, string, User> echoUserMethod = controller.EchoUser; ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method }; ParameterInfo parameterInfo = echoUserMethod.Method.GetParameters()[0]; ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo); Assert.Equal(actionDescriptor, parameterDescriptor.ActionDescriptor); Assert.Null(parameterDescriptor.DefaultValue); Assert.Equal(parameterInfo, parameterDescriptor.ParameterInfo); Assert.Equal(parameterInfo.Name, parameterDescriptor.ParameterName); Assert.Equal(typeof(string), parameterDescriptor.ParameterType); Assert.Null(parameterDescriptor.Prefix); Assert.Null(parameterDescriptor.ModelBinderAttribute); }
public void Descriptions_RecognizesDirectRoutes() { var config = new HttpConfiguration(); var routeTemplate = "api/values"; var controllerDescriptor = new HttpControllerDescriptor(config, "ApiExplorerValues", typeof(ApiExplorerValuesController)); var action = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(ApiExplorerValuesController).GetMethod("Get")); var actions = new ReflectedHttpActionDescriptor[] { action }; config.Routes.Add("Route", new HttpDirectRoute(routeTemplate, 0, actions)); var descriptions = new ApiExplorer(config).ApiDescriptions; ApiDescription description = Assert.Single(descriptions); Assert.Equal(HttpMethod.Get, description.HttpMethod); Assert.Equal(routeTemplate, description.RelativePath); Assert.Equal(action, description.ActionDescriptor); }
private HttpActionDescriptor CreateBetaAction(HttpActionDescriptor originalAction) { var attributes = originalAction.GetCustomAttributes<HasBetaTestingActionAttribute>().OfType<HasBetaTestingActionAttribute>(); if (!attributes.Any()) { return null; } var methodName = attributes.First().MethodName; var actionMethod = originalAction.ControllerDescriptor.ControllerType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic); if (actionMethod == null) { return null; } var actionDescriptor = new ReflectedHttpActionDescriptor(originalAction.ControllerDescriptor, actionMethod); actionDescriptor.Properties.TryAdd("IsBetaAction", true); return actionDescriptor; }
public void DifferentReturnTypeWorks(string methodName, object responseObject, bool isNoOp) { // Arrange QueryableAttribute attribute = new QueryableAttribute(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer/?$orderby=Name"); HttpConfiguration config = new HttpConfiguration(); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; HttpControllerContext controllerContext = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request); HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerHighLevel", typeof(CustomerHighLevelController)); HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(CustomerHighLevelController).GetMethod(methodName)); HttpActionContext actionContext = new HttpActionContext(controllerContext, actionDescriptor); HttpActionExecutedContext context = new HttpActionExecutedContext(actionContext, null); context.Response = new HttpResponseMessage(HttpStatusCode.OK); context.Response.Content = new ObjectContent(typeof(object), responseObject, new JsonMediaTypeFormatter()); // Act and Assert attribute.OnActionExecuted(context); Assert.Equal(HttpStatusCode.OK, context.Response.StatusCode); Assert.True(context.Response.Content is ObjectContent); Assert.Equal(isNoOp, ((ObjectContent)context.Response.Content).Value == responseObject); }
public void GetEdmModelForMultipleTypesWorks() { // Arrange HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerLowLevel", typeof(CustomerHighLevelController)); HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(CustomerHighLevelController).GetMethod("GetObject")); Type type1 = typeof(Customer); Type type2 = typeof(BellevueCustomer); // Act IEdmModel model1 = actionDescriptor.GetEdmModel(type1); IEdmModel model2 = actionDescriptor.GetEdmModel(type2); // Assert Assert.NotSame(model1, model2); Assert.NotNull(model1); Assert.Equal(2, model1.SchemaElements.Count()); Assert.Equal(type1.Name, model1.SchemaElements.First().Name); Assert.NotNull(model2); Assert.Equal(2, model2.SchemaElements.Count()); Assert.Equal(type2.Name, model2.SchemaElements.First().Name); }
static void ResolveActionScopedNoopFilterOverrides(FilterContext filterContext, ReflectedHttpActionDescriptor descriptor) { ResolveActionScopedOverrideFilter(filterContext, descriptor.MethodInfo, ActionFilterOverrideMetadataKey); ResolveActionScopedOverrideFilter(filterContext, descriptor.MethodInfo, AuthenticationFilterOverrideMetadataKey); ResolveActionScopedOverrideFilter(filterContext, descriptor.MethodInfo, AuthorizationFilterOverrideMetadataKey); ResolveActionScopedOverrideFilter(filterContext, descriptor.MethodInfo, ExceptionFilterOverrideMetadataKey); }
public DescribedHttpActionInfo(HttpActionDescriptor actionDescr, ControllerInfo controller) : base(controller) { this.actionDescr = actionDescr; this.reflectedActionDescr = this.actionDescr as ReflectedHttpActionDescriptor; }