public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }//, //constraints:new{sss=new HttpMethodConstraint(HttpMethod.Post)} ); HttpRouteValueDictionary defaults = new HttpRouteValueDictionary(); //defaults.Add("controller", "Demo"); //defaults.Add("action", "Get"); defaults.Add("val", 0); HttpRouteValueDictionary constraints = new HttpRouteValueDictionary(); constraints.Add("val",new DoubleRouteConstraint()); HttpRoute route = new HttpRoute("customer/{controller}/{action}/{val}", defaults, constraints); config.Routes.Add("CustomerApi",route); }
public static void Register(HttpConfiguration config) { var emptyDictionary = new HttpRouteValueDictionary(); // Add our one HttpMessageHandler to the root path. config.Routes.MapHttpRoute("index", "", emptyDictionary, emptyDictionary, new HelloWorldHandler()); }
/// <summary> /// Map odata route with query string or header constraints /// </summary> public static void MapODataRoute( this HttpRouteCollection routes, string routeName, string routePrefix, IEdmModel model, IODataPathHandler pathHandler, IEnumerable<IODataRoutingConvention> routingConventions, object queryConstraints, object headerConstraints) { if (routes == null) { throw new ArgumentNullException("routes"); } string routeTemplate = string.IsNullOrEmpty(routePrefix) ? ODataRouteConstants.ODataPathTemplate : (routePrefix + "/" + ODataRouteConstants.ODataPathTemplate); ODataVersionRouteConstraint routeConstraint = new ODataVersionRouteConstraint(pathHandler, model, routeName, routingConventions, queryConstraints, headerConstraints); var constraints = new HttpRouteValueDictionary(); constraints.Add(ODataRouteConstants.ConstraintName, routeConstraint); routes.MapHttpRoute( routeName, routeTemplate, defaults: null, constraints: constraints); }
/// <summary> /// Builds an <see cref="IHttpRoute"/>. /// </summary> /// <param name="routeTemplate">The detokenized route template.</param> /// <param name="defaults">The route defaults.</param> /// <param name="constraints">The route constraints.</param> /// <param name="actions">The actions to invoke for the route.</param> /// <returns>The generated <see cref="IHttpRoute"/>.</returns> public virtual IHttpRoute BuildHttpRoute( string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, IEnumerable<ReflectedHttpActionDescriptor> actions) { return new HttpDirectRoute(routeTemplate, defaults, constraints, actions); }
/// <summary> /// Route used by the AttributeRouting framework in self-host projects. /// </summary> public HttpAttributeRoute(string url, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpConfigurationBase configuration) : base(url, defaults, constraints, dataTokens, configuration.MessageHandler) { _configuration = configuration; }
/// <summary> /// Route used by the AttributeRouting framework in self-host projects. /// </summary> public HttpAttributeRoute(string url, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpAttributeRoutingConfiguration configuration) : base(url, defaults, constraints, dataTokens) { _configuration = configuration; }
public ODataVersionRouteConstraint( string routeName, object queryConstraints, object headerConstraints) : base(routeName) { QueryStringConstraints = new HttpRouteValueDictionary(queryConstraints); HeaderConstraints = new HttpRouteValueDictionary(headerConstraints); }
public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens) { _routeTemplate = String.IsNullOrWhiteSpace(routeTemplate) ? String.Empty : routeTemplate; _defaults = defaults ?? new HttpRouteValueDictionary(); _constraints = constraints ?? new HttpRouteValueDictionary(); _dataTokens = dataTokens ?? new HttpRouteValueDictionary(); // The parser will throw for invalid routes. _parsedRoute = HttpRouteParser.Parse(_routeTemplate); }
private static decimal GetPrecedence(string attributeRouteTemplate) { DefaultInlineConstraintResolver resolver = new DefaultInlineConstraintResolver(); HttpRouteValueDictionary defaults = new HttpRouteValueDictionary(); HttpRouteValueDictionary constraints = new HttpRouteValueDictionary(); string standardRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(attributeRouteTemplate, defaults, constraints, new DefaultInlineConstraintResolver()); HttpParsedRoute parsedRoute = HttpRouteParser.Parse(standardRouteTemplate); return parsedRoute.GetPrecedence(constraints); }
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); }
/// <summary> /// Initializes a new instance of the <see cref="ODataRoute" /> class. /// </summary> /// <param name="routePrefix">The route prefix.</param> /// <param name="pathConstraint">The OData path constraint.</param> /// <param name="defaults">The default values for the route.</param> /// <param name="constraints">The route constraints.</param> /// <param name="dataTokens">The data tokens.</param> /// <param name="handler">The message handler for the route.</param> public ODataRoute( string routePrefix, ODataPathRouteConstraint pathConstraint, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler) : this(routePrefix, (IHttpRouteConstraint)pathConstraint, defaults, constraints, dataTokens, handler) { }
public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler) { _routeTemplate = routeTemplate == null ? String.Empty : routeTemplate; _defaults = defaults ?? new HttpRouteValueDictionary(); _constraints = constraints ?? new HttpRouteValueDictionary(); _dataTokens = dataTokens ?? new HttpRouteValueDictionary(); Handler = handler; // The parser will throw for invalid routes. ParsedRoute = HttpRouteParser.Parse(RouteTemplate); }
public void Constructor_IsCaseInsensitive() { // Arrange HttpRouteValueDictionary routeValues = new HttpRouteValueDictionary(); // Act routeValues.Add("KEY", null); // Assert Assert.True(routeValues.ContainsKey("key")); }
/// <summary> /// /// </summary> /// <param name="routes"></param> /// <param name="name"></param> /// <param name="routeTemplate"></param> /// <param name="defaults"></param> /// <param name="constraints"></param> /// <param name="handler"></param> /// <param name="namespaces"></param> /// <returns></returns> public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler, string[] namespaces) { if (routes == null) { throw new ArgumentNullException("routes"); } var routeValue = new HttpRouteValueDictionary(new { Namespace = namespaces });//设置路由值 var route = routes.CreateRoute(routeTemplate, new HttpRouteValueDictionary(defaults), new HttpRouteValueDictionary(constraints), routeValue, handler); routes.Add(name, route); return route; }
public ODataVersionRouteConstraint( IODataPathHandler pathHandler, IEdmModel model, string routeName, IEnumerable<IODataRoutingConvention> routingConventions, object queryConstraints, object headerConstraints) : base(pathHandler, model, routeName, routingConventions) { QueryStringConstraints = new HttpRouteValueDictionary(queryConstraints); HeaderConstraints = new HttpRouteValueDictionary(headerConstraints); }
/// <summary> /// Maps the specified route template and sets default route values, constraints, and end-point message handler. /// </summary> /// <param name="routes">A collection of routes for the application.</param> /// <param name="name">The name of the route to map.</param> /// <param name="routeTemplate">The route template for the route.</param> /// <param name="defaults">An object that contains default route values.</param> /// <param name="constraints">A set of expressions that specify values for <paramref name="routeTemplate"/>.</param> /// <param name="handler">The handler to which the request will be dispatched.</param> /// <returns>A reference to the mapped route.</returns> public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler) { if (routes == null) { throw Error.ArgumentNull("routes"); } HttpRouteValueDictionary defaultsDictionary = new HttpRouteValueDictionary(defaults); HttpRouteValueDictionary constraintsDictionary = new HttpRouteValueDictionary(constraints); IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: null, handler: handler); routes.Add(name, route); return route; }
/// <summary> /// Initializes a new instance of the <see cref="HttpDirectRoute" /> class. /// </summary> /// <param name="routeTemplate">The route template.</param> /// <param name="defaults">The default values.</param> /// <param name="constraints">The route constraints.</param> /// <param name="actions">The actions that are reachable via this route.</param> public HttpDirectRoute( string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, IEnumerable<ReflectedHttpActionDescriptor> actions) : base(routeTemplate, defaults: defaults, constraints: constraints, dataTokens: null, handler: null) { if (actions != null) { Actions = actions.AsArray(); DataTokens[RouteKeys.ActionsDataTokenKey] = Actions; } }
/// <summary> /// Maps the specified route template and sets default route values, constraints, namespaces, and end-point message handler. /// </summary> /// <param name="routes">A collection of routes for the application.</param> /// <param name="name">The name of the route to map.</param> /// <param name="routeTemplate">The route template for the route.</param> /// <param name="defaults">An object that contains default route values.</param> /// <param name="constraints">A set of expressions that specify values for <paramref name="routeTemplate"/>.</param> /// <param name="handler">The handler to which the request will be dispatched.</param> /// <returns>A reference to the mapped route.</returns> public static Route MapHttpRoute(this RouteCollection routes, string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler) { if (routes == null) { throw Error.ArgumentNull("routes"); } HttpRouteValueDictionary defaultsDictionary = new HttpRouteValueDictionary(defaults); HttpRouteValueDictionary constraintsDictionary = new HttpRouteValueDictionary(constraints); HostedHttpRoute httpRoute = (HostedHttpRoute)GlobalConfiguration.Configuration.Routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: null, handler: handler); Route route = httpRoute.OriginalRoute; routes.Add(name, route); return route; }
/// <summary> /// Maps the specified OData route. /// </summary> /// <param name="routes">A collection of routes for the application.</param> /// <param name="routeName">The name of the route to map.</param> /// <param name="routePrefix">The prefix to add to the OData route's path template.</param> /// <param name="model">The EDM model to use for parsing OData paths.</param> /// <param name="pathHandler">The <see cref="IODataPathHandler"/> to use for parsing the OData path.</param> /// <param name="routingConventions">The OData routing conventions to use for controller and action selection.</param> public static void MapODataRoute(this HttpRouteCollection routes, string routeName, string routePrefix, IEdmModel model, IODataPathHandler pathHandler, IEnumerable<IODataRoutingConvention> routingConventions) { if (routes == null) { throw Error.ArgumentNull("routes"); } string routeTemplate = String.IsNullOrEmpty(routePrefix) ? ODataRouteConstants.ODataPathTemplate : routePrefix + "/" + ODataRouteConstants.ODataPathTemplate; IHttpRouteConstraint routeConstraint = new ODataPathRouteConstraint(pathHandler, model, routeName, routingConventions); HttpRouteValueDictionary constraintDictionary = new HttpRouteValueDictionary() { { ODataRouteConstants.ConstraintName, routeConstraint } }; routes.MapHttpRoute(routeName, routeTemplate, defaults: null, constraints: constraintDictionary); }
private static HttpRouteValueDictionary BuildHttpRouteValueDictionary(IEnumerable<RouteConfigurationParameter> defaultParameters) { var result = new HttpRouteValueDictionary(); foreach (var defaultParameter in defaultParameters) { var value = defaultParameter.IsOptional ? RouteParameter.Optional : defaultParameter.Value; result.Add(defaultParameter.Name, value); } return result; }
public HttpRouteData(IHttpRoute route, HttpRouteValueDictionary values) { if (route == null) { throw Error.ArgumentNull("route"); } if (values == null) { throw Error.ArgumentNull("values"); } _route = route; _values = values; }
private static decimal Compute(string template) { DefaultInlineConstraintResolver resolver = new DefaultInlineConstraintResolver(); #if ASPNETWEBAPI HttpRouteValueDictionary defaults = new HttpRouteValueDictionary(); HttpRouteValueDictionary constraints = new HttpRouteValueDictionary(); #else RouteValueDictionary defaults = new RouteValueDictionary(); RouteValueDictionary constraints = new RouteValueDictionary(); #endif string standardRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(template, defaults, constraints, new DefaultInlineConstraintResolver()); var parsedRoute = RouteParser.Parse(standardRouteTemplate); return RoutePrecedence.Compute(parsedRoute, constraints); }
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); }
public override object CreateRoute(RouteSettings routeSettings, RegisterSettings registerSettings) { var defaults = new HttpRouteValueDictionary(routeSettings.Defaults); var constraints = new HttpRouteValueDictionary(routeSettings.Constraints); var dataTokens = new HttpRouteValueDictionary(routeSettings.DataTokens); return new CodeHttpRoute(routeSettings.RouteTemplate, defaults, constraints, dataTokens) { ActionMapping = routeSettings.ActionMapping, ControllerMapping = routeSettings.ControllerMapping, ControllerDescriptors = routeSettings.Actions .Select(a => a.Controller) .DistinctReference() .ToDictionary(c => c.Name, c => ((DescribedHttpControllerInfo)c).Descriptor, StringComparer.OrdinalIgnoreCase) }; }
/// <summary> /// Builds an <see cref="IHttpRoute"/> for a particular action. /// </summary> /// <param name="routeTemplate">The tokenized route template for the route.</param> /// <param name="actions">The actions to invoke for the route.</param> /// <returns>The generated <see cref="IHttpRoute"/>.</returns> public virtual IHttpRoute BuildHttpRoute( string routeTemplate, IEnumerable<ReflectedHttpActionDescriptor> actions) { if (routeTemplate == null) { throw Error.ArgumentNull("routeTemplate"); } HttpRouteValueDictionary defaults = new HttpRouteValueDictionary(); HttpRouteValueDictionary constraints = new HttpRouteValueDictionary(); string detokenizedRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(routeTemplate, defaults, constraints, ConstraintResolver); return BuildHttpRoute(detokenizedRouteTemplate, defaults, constraints, actions); }
private static void Add(this MultipartFormDataContent form, HttpContent content, object formValues, string name = null, string fileName = null) { var header = new ContentDispositionHeaderValue("form-data"); header.Name = name; header.FileName = fileName; header.FileNameStar = fileName; var headerParameters = new HttpRouteValueDictionary(formValues); foreach (var parameter in headerParameters) { header.Parameters.Add(new NameValueHeaderValue(parameter.Key, parameter.Value.ToString())); } content.Headers.ContentDisposition = header; form.Add(content); }
public void CreateRoute_ValidatesConstraintType_StringRegex() { // Arrange var routes = new MockHttpRouteCollection(); var constraint = "product|products"; var constraints = new HttpRouteValueDictionary(); constraints.Add("custom", constraint); // Act var route = routes.CreateRoute("{controller}/{id}", null, constraints); // Assert Assert.NotNull(route.Constraints["custom"]); Assert.Equal(1, routes.TimesValidateConstraintCalled); }
public HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) { var allRouteValues = new HttpRouteValueDictionary(routeValues); var segments = portalAliasInfo.HTTPAlias.Split('/'); if(segments.Length > 1) { for(int i = 1; i < segments.Length; i++) { var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); var value = segments[i]; allRouteValues.Add(key, value); } } return allRouteValues; }
internal HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler, HttpParsedRoute parsedRoute) { _routeTemplate = routeTemplate == null ? String.Empty : routeTemplate; _defaults = defaults ?? new HttpRouteValueDictionary(); _constraints = constraints ?? new HttpRouteValueDictionary(); _dataTokens = dataTokens ?? new HttpRouteValueDictionary(); Handler = handler; if (parsedRoute == null) { // The parser will throw for invalid routes. ParsedRoute = RouteParser.Parse(routeTemplate); } else { ParsedRoute = parsedRoute; } }
public void GetVirtualPath_GetsValuesInCaseInsensitiveWay(string controllerKey) { var route = new HttpRoute("{controller}"); var request = new HttpRequestMessage(); request.SetRouteData( new HttpRouteData(route, new HttpRouteValueDictionary() { { "controller", "Employees" } })); var values = new HttpRouteValueDictionary() { { "httproute", true }, { controllerKey, "Customers" } }; IHttpVirtualPathData virtualPath = route.GetVirtualPath(request, values); Assert.NotNull(virtualPath); Assert.Equal("Customers", virtualPath.VirtualPath); }
public void GenerateSwaggerDocument_CreatesBasicSwaggerDocument() { string apiEndpoint = "/api/HttpTriggerCSharp1"; string routeTemplate = apiEndpoint.Substring(1); HttpMethod[] allowedMethods = { HttpMethod.Get }; var httpMethodConstraint = new HttpMethodConstraint(allowedMethods); HttpRouteValueDictionary constraints = new HttpRouteValueDictionary(); constraints.Add(ScriptConstants.HttpMethodConstraintName, httpMethodConstraint); var httpRoute = new HttpRoute(routeTemplate, null, constraints); Dictionary <IHttpRoute, FunctionDescriptor> httpFunctions = new Dictionary <IHttpRoute, FunctionDescriptor>() { { httpRoute, new FunctionDescriptor("HttpTriggerCSharp1", null, new FunctionMetadata(), null) } }; // Act var swaggerDocumentManager = new SwaggerDocumentManager(_scriptConfig); var generatedDocument = swaggerDocumentManager.GenerateSwaggerDocument(httpFunctions); string hostName = Environment.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHostName); if (hostName == null) { generatedDocument["info"]["title"] = string.Empty; generatedDocument["host"] = string.Empty; } string expectedSwagger = @" { 'swagger': '2.0', 'info': { 'title': 'localhost', 'version': '1.0.0' }, 'host': 'localhost', 'basePath': '/', 'schemes': [ 'https', 'http' ], 'paths': { '/api/HttpTriggerCSharp1': { 'get': { 'operationId': '/api/HttpTriggerCSharp1/get', 'produces': [], 'consumes': [], 'parameters': [], 'description': 'Replace with Operation Object #http://swagger.io/specification/#operationObject', 'responses': { '200': { 'description': 'Success operation' } }, 'security': [ { 'apikeyQuery': [] } ] } } }, 'definitions': {}, 'securityDefinitions': { 'apikeyQuery': { 'type': 'apiKey', 'name': 'code', 'in': 'query' } } }".Replace("localhost", hostName); expectedSwagger = JObject.Parse(expectedSwagger).ToString(Formatting.None); Assert.Equal(expectedSwagger, generatedDocument.ToString(Formatting.None)); }