protected bool TestValue(IHttpRouteConstraint constraint, object value) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(); HttpRoute httpRoute = new HttpRoute(); const string parameterName = "fake"; HttpRouteValueDictionary values = new HttpRouteValueDictionary { { parameterName, value } }; const HttpRouteDirection httpRouteDirection = HttpRouteDirection.UriResolution; return constraint.Match(httpRequestMessage, httpRoute, parameterName, values, httpRouteDirection); }
private long GetLastUpdate(IDictionary <HttpRoute, long> updates, HttpRoute route) { long lastUpdate = updates.Get(route); if (lastUpdate == null) { lastUpdate = Sharpen.Extensions.ValueOf(0L); } return(lastUpdate); }
public void ShouldSetRouteDataWithControllerInformationWhenConfigureIsInvoked() { controller = new DummyController(); var route = new HttpRoute("testroute"); controller.ConfigureForTesting(new HttpRequestMessage(), "testroute", route); var addedRoute = controller.Configuration.Routes["testroute"]; addedRoute.ShouldEqual(route); }
protected void SetUpCustomRouteFor <TController>(string routeTemplate) where TController : ApiController { var controllerName = typeof(TController).Name.ToLower().Replace("controller", String.Empty); var route = new HttpRoute( routeTemplate, new HttpRouteValueDictionary(new { controller = controllerName, id = RouteParameter.Optional })); Configuration.Routes.Add(controllerName, route); }
public void should_get_internal_server_error_when_exception_occurs() { var matchedRoute = new HttpRoute(typeof(ControllerWithErrorAction), "Get", HttpMethod.Get); var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver(controllerTypeResolver.GetControllerTypes(ControllerAssemblies)); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, resolver); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); }
public void should_return_method_not_allowed_if_method_mismatches() { var matchedRoute = new HttpRoute(typeof(ControllerWithMismatchedMethod), "Post", HttpMethod.Post); var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver(controllerTypeResolver.GetControllerTypes(ControllerAssemblies)); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, resolver); Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode); }
public void should_only_invoke_public_instance_method() { var matchedRoute = new HttpRoute(typeof(ControllerWithNonPublicAction), "Get", HttpMethod.Get); var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver(controllerTypeResolver.GetControllerTypes(ControllerAssemblies)); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, resolver); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }
public void should_invoke_case_insensitively() { var matchedRoute = new HttpRoute(typeof(ControllerWithPublicAction), "GET", HttpMethod.Get); var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver(controllerTypeResolver.GetControllerTypes(ControllerAssemblies)); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, resolver); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
public void Register_WithValidHttpConfiguration_RegistersDefaultApiRoute() { HttpRouteCollection routes = new HttpRouteCollection(); HttpConfiguration configuration = new HttpConfiguration(routes); WebApiConfig.Register(configuration); HttpRoute defaultRoute = routes.SingleOrDefault(route => route.RouteTemplate == "api/{controller}/{id}") as HttpRoute; Assert.IsNotNull(defaultRoute); }
public void should_only_register_public_controller() { var matchedRoute = new HttpRoute(typeof(NonPublicController), "Get", HttpMethod.Get); var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver(controllerTypeResolver.GetControllerTypes(ControllerAssemblies)); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, resolver); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); }
public static void Register(HttpConfiguration configuration) { configuration.MapHttpAttributeRoutes(); configuration.Routes.MapHttpRoute("Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); HttpRoute httpRoute = new HttpRoute("api/{controller}/{id}", new HttpRouteValueDictionary(new { id = RouteParameter.Optional })); configuration.Routes.Add("second", httpRoute); JsonMediaTypeFormatter jsonMediaType = configuration.Formatters.JsonFormatter; jsonMediaType.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }
protected void SetUpDefaultRoutesFor(IEnumerable <Type> controllerTypes) { foreach (var type in controllerTypes) { var controllerName = type.Name.ToLower().Replace("controller", String.Empty); var route = new HttpRoute( String.Format("{0}/{{id}}", controllerName), new HttpRouteValueDictionary(new { controller = controllerName, id = RouteParameter.Optional })); Configuration.Routes.Add(controllerName, route); } }
protected bool TestValue(IHttpRouteConstraint constraint, object value) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(); HttpRoute httpRoute = new HttpRoute(); const string parameterName = "fake"; HttpRouteValueDictionary values = new HttpRouteValueDictionary { { parameterName, value } }; const HttpRouteDirection httpRouteDirection = HttpRouteDirection.UriResolution; return(constraint.Match(httpRequestMessage, httpRoute, parameterName, values, httpRouteDirection)); }
public void should_return_internal_server_error_if_no_controller_is_found() { var matchedRoute = new HttpRoute(typeof(ControllerWithoutAction), "Get", HttpMethod.Get); var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver( controllerTypeResolver.GetControllerTypes(new[] { Assembly.GetExecutingAssembly() })); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, resolver); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); }
public static void LogTo(this HttpRoute route, TextWriter writer) { var attributeRoute = route as IAttributeRoute; var info = RouteLoggingInfo.GetRouteInfo(route.RouteTemplate, route.Defaults, attributeRoute.SafeGet(r => r.QueryStringDefaults), route.Constraints, attributeRoute.SafeGet(r => r.QueryStringConstraints), route.DataTokens); LogWriter.LogRoute(writer, route.RouteTemplate, info); }
public void should_get_null_if_request_method_does_not_match() { var routes = new HttpRouteCollection(); var expectedRoute = new HttpRoute("ControllerName", "ActionName", HttpMethod.Post, "resource"); routes.Add(expectedRoute); HttpRoute route = routes.GetRouteData( new HttpRequestMessage(HttpMethod.Get, "http://www.base.com/resource")); Assert.Null(route); }
public void should_get_route_if_request_uri_matches_and_constraint_matches() { var routes = new HttpRouteCollection(); var expectedRoute = new HttpRoute("ControllerName", "ActionName", HttpMethod.Get, "resource"); routes.Add(expectedRoute); HttpRoute route = routes.GetRouteData( new HttpRequestMessage(HttpMethod.Get, "http://www.base.com/resource")); Assert.Same(expectedRoute, route); }
private HttpServer GetTestCitiesServer(HttpConfiguration config) { HttpControllerDispatcher dispatcher = new HttpControllerDispatcher(config); HttpRoute route = new HttpRoute("{controller}/{action}", new HttpRouteValueDictionary("Cities")); config.Routes.Add("cities", route); HttpServer server = new HttpServer(config, dispatcher); return(server); }
/// <summary>Creates a tunnel to an intermediate proxy.</summary> /// <remarks> /// Creates a tunnel to an intermediate proxy. /// This method is <i>not</i> implemented in this class. /// It just throws an exception here. /// </remarks> /// <exception cref="Apache.Http.HttpException"></exception> private bool CreateTunnelToProxy(HttpRoute route, int hop, HttpClientContext context ) { // Have a look at createTunnelToTarget and replicate the parts // you need in a custom derived class. If your proxies don't require // authentication, it is not too hard. But for the stock version of // HttpClient, we cannot make such simplifying assumptions and would // have to include proxy authentication code. The HttpComponents team // is currently not in a position to support rarely used code of this // complexity. Feel free to submit patches that refactor the code in // createTunnelToTarget to facilitate re-use for proxy tunnelling. throw new HttpException("Proxy chains are not supported."); }
private static void ExecuteProcess(HttpListenerContext context, Message message) { Logger.DebugFormat("Entry Url={0}", context.Request.Url); IModule module = null; try { // Reflection var plusRoute = new HttpRoute { Host = "+", Path = context.Request.Url.LocalPath, Port = context.Request.Url.Port }; var route = new HttpRoute { Host = context.Request.Url.Host, Path = context.Request.Url.LocalPath, Port = context.Request.Url.Port }; Type type; if (!RoutesConfig.ConfiguredRoutes.TryGetValue(plusRoute, out type)) { if (!RoutesConfig.ConfiguredRoutes.TryGetValue(route, out type)) { throw new ModuleConfigurationException(String.Format("Could not find module for route={0}", route), null); } } Logger.DebugFormat("Configured Module={0}", type.FullName); var ctor = type.GetConstructor(new Type[0]); module = (IModule)ctor.Invoke(new object[0]); // Process Logger.DebugFormat("Message process executing."); module.Process(message); Logger.DebugFormat("Message process performed."); } catch (Exception e) { Logger.Error(message.ToString(), e); if (module != null) { module.ExceptionHandling(e, message); } else { message.SetPayload(e.ToString()); } } }
public void should_return_method_not_allowed_for_non_annotated_method() { var matchedRoute = new HttpRoute("ControllerWithoutMethodAnnotation", "Get", HttpMethod.Get); ICollection <Type> controllerTypes = new DefaultHttpControllerTypeResolver() .GetControllerTypes(ControllerAssemblies); var resolver = new DefaultDependencyResolver(controllerTypes); var factory = new DefaultControllerFactory(); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, controllerTypes, resolver, factory); Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode); }
public void should_invoke_method_with_multiple_methods(string method) { var matchedRoute = new HttpRoute( typeof(ControllerWithMultipleMethodAnnotation), "Invoke", new HttpMethod(method)); var controllerTypeResolver = new DefaultHttpControllerTypeResolver(); var resolver = new DefaultDependencyResolver(controllerTypeResolver.GetControllerTypes(ControllerAssemblies)); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, resolver); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
/// <summary> /// Validates that a constraint is valid for an <see cref="IHttpRoute"/> created by a call /// to the <see cref="HttpRouteCollection.CreateRoute(string, IDictionary<string, object>, IDictionary<string, object>, IDictionary<string, object>, HttpMessageHandler)"/> method. /// </summary> /// <param name="routeTemplate">The route template.</param> /// <param name="name">The constraint name.</param> /// <param name="constraint">The constraint object.</param> /// <remarks> /// Implement this method when deriving from <see cref="HttpRouteCollection"/> to allow contraints of /// types other than <see cref="string"/> and <see cref="IHttpRouteConstraint"/>. /// </remarks> protected virtual void ValidateConstraint(string routeTemplate, string name, object constraint) { if (name == null) { throw Error.ArgumentNull("name"); } if (constraint == null) { throw Error.ArgumentNull("constraint"); } HttpRoute.ValidateConstraint(routeTemplate, name, constraint); }
public void Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string decodedId) { var handler = CreateOKHandlerStub(); var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false); var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers/" + decodedId); var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector); var route = new HttpRoute("api/customers/{id}"); adapter.Invoke(new OwinContext(environment)).Wait(); IHttpRouteData routeData = route.GetRouteData("/vroot", handler.Request); Assert.NotNull(routeData); Assert.Equal(decodedId, routeData.Values["id"]); }
public void should_invoke_case_insensitively() { var matchedRoute = new HttpRoute("ControllerWithPublicAction", "GET", HttpMethod.Get); ICollection <Type> controllerTypes = new DefaultHttpControllerTypeResolver() .GetControllerTypes(ControllerAssemblies); var resolver = new DefaultDependencyResolver(controllerTypes); var factory = new DefaultControllerFactory(); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, controllerTypes, resolver, factory); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
public void should_only_invoke_public_instance_method() { var matchedRoute = new HttpRoute("ControllerWithNonPublicAction", "Get", HttpMethod.Get); ICollection <Type> controllerTypes = new DefaultHttpControllerTypeResolver() .GetControllerTypes(ControllerAssemblies); var resolver = new DefaultDependencyResolver(controllerTypes); var factory = new DefaultControllerFactory(); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, controllerTypes, resolver, factory); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }
public void should_only_register_public_controller() { var matchedRoute = new HttpRoute("NonPublicController", "Get", HttpMethod.Get); ICollection <Type> controllerTypes = new DefaultHttpControllerTypeResolver() .GetControllerTypes(ControllerAssemblies); var resolver = new DefaultDependencyResolver(controllerTypes); var factory = new DefaultControllerFactory(); HttpResponseMessage response = ControllerActionInvoker.InvokeAction( matchedRoute, controllerTypes, resolver, factory); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); }
public void GetVirtualPath_GeneratesPathWithoutRouteData() { var route = new HttpRoute("{controller}"); var request = new HttpRequestMessage(); var values = new HttpRouteValueDictionary() { { "httproute", true }, { "controller", "Customers" } }; IHttpVirtualPathData virtualPath = route.GetVirtualPath(request, values); Assert.NotNull(virtualPath); Assert.Equal("Customers", virtualPath.VirtualPath); }
private async Task <HttpResponseMessage> GetCollectionRawResponse(string collectionName = collectionName, HttpMethod httpMethod = null) { HttpRequestMessage requestMessage = new HttpRequestMessage(httpMethod ?? HttpMethod.Get, "http://localhost/collection/" + collectionName); requestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); var route = new HttpRoute("collection/{collectionName}"); var routeValues = new HttpRouteValueDictionary() { { "collectionName", collectionName } }; var routeData = new HttpRouteData(route, routeValues); requestMessage.SetRouteData(routeData); return(await getCollectionService.Execute(requestMessage)); }
public void GetRouteDataDoesNotMatch(string uriTemplate, string virtualPathRoot, string requestUri) { HttpRoute route = new HttpRoute(uriTemplate); route.Defaults.Add("controller", "Customer"); route.Defaults.Add("id", "999"); HttpRequestMessage request = new HttpRequestMessage(); request.RequestUri = new Uri(requestUri); IHttpRouteData data = route.GetRouteData(virtualPathRoot, request); // Assert Assert.Null(data); }
public virtual void BackOff(HttpRoute route) { lock (connPerRoute) { int curr = connPerRoute.GetMaxPerRoute(route); long lastUpdate = GetLastUpdate(lastRouteBackoffs, route); long now = clock.GetCurrentTime(); if (now - lastUpdate < coolDown) { return; } connPerRoute.SetMaxPerRoute(route, GetBackedOffPoolSize(curr)); lastRouteBackoffs.Put(route, Sharpen.Extensions.ValueOf(now)); } }
public void SubRouteCollection_Throws_OnDuplicateNamedRoute_WebAPI() { // Arrange var collection = new SubRouteCollection(); var route1 = new HttpRoute("api/Person"); var route2 = new HttpRoute("api/Car"); collection.Add(new RouteEntry("route", route1)); var expectedError = "A route named 'route' is already in the route collection. Route names must be unique.\r\n\r\n" + "Duplicates:" + Environment.NewLine + "api/Car" + Environment.NewLine + "api/Person"; // Act & Assert Assert.Throws<InvalidOperationException>(() => collection.Add(new RouteEntry("route", route2)), expectedError); }
/// <inheritdoc/> public virtual RouteEntry Build() { if (ParsedRoute == null) { ParsedRoute = RouteParser.Parse(Template); } ValidateParameters(ParsedRoute); TRouteDictionaryConcrete defaults; #if ASPNETWEBAPI defaults = Copy(Defaults); #else defaults = Copy(Defaults) ?? new RouteValueDictionary(); #endif TRouteDictionaryConcrete constraints = Copy(Constraints); TRouteDictionaryConcrete dataTokens = Copy(DataTokens) ?? new TRouteDictionaryConcrete(); dataTokens[RouteDataTokenKeys.Actions] = _actions; int order = Order; if (order != default(int)) { dataTokens[RouteDataTokenKeys.Order] = order; } decimal precedence = Precedence; if (precedence != default(decimal)) { dataTokens[RouteDataTokenKeys.Precedence] = precedence; } #if ASPNETWEBAPI if (constraints != null) { foreach (var constraint in constraints) { HttpRoute.ValidateConstraint(Template, constraint.Key, constraint.Value); } } HttpMessageHandler handler = null; IHttpRoute route = new HttpRoute(Template, defaults, constraints, dataTokens, handler, ParsedRoute); #else ControllerDescriptor controllerDescriptor = GetControllerDescriptor(); if (controllerDescriptor != null) { defaults["controller"] = controllerDescriptor.ControllerName; } if (TargetIsAction && _actions.Length == 1) { ActionDescriptor actionDescriptor = _actions[0]; defaults["action"] = actionDescriptor.ActionName; dataTokens[RouteDataTokenKeys.TargetIsAction] = true; } RouteAreaAttribute area = controllerDescriptor.GetAreaFrom(); string areaName = controllerDescriptor.GetAreaName(area); if (areaName != null) { dataTokens[RouteDataTokenKeys.Area] = areaName; dataTokens[RouteDataTokenKeys.UseNamespaceFallback] = false; Type controllerType = controllerDescriptor.ControllerType; if (controllerType != null) { dataTokens[RouteDataTokenKeys.Namespaces] = new[] { controllerType.Namespace }; } } Route route = new Route(Template, defaults, constraints, dataTokens, routeHandler: null); ConstraintValidation.Validate(route); #endif return new RouteEntry(Name, route); }