本文整理汇总了C#中HttpRouteValueDictionary.Add方法的典型用法代码示例。如果您正苦于以下问题:C# HttpRouteValueDictionary.Add方法的具体用法?C# HttpRouteValueDictionary.Add怎么用?C# HttpRouteValueDictionary.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpRouteValueDictionary
的用法示例。
在下文中一共展示了HttpRouteValueDictionary.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MapODataRoute
/// <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);
}
示例2: Register
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);
}
示例3: Constructor_IsCaseInsensitive
public void Constructor_IsCaseInsensitive()
{
// Arrange
HttpRouteValueDictionary routeValues = new HttpRouteValueDictionary();
// Act
routeValues.Add("KEY", null);
// Assert
Assert.True(routeValues.ContainsKey("key"));
}
示例4: CreateRoute_ValidatesConstraintType_StringRegex
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);
}
示例5: GetAllRouteValues
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;
}
示例6: MatchContentPathSegment
private static bool MatchContentPathSegment(PathContentSegment routeSegment, string requestPathSegment, HttpRouteValueDictionary defaultValues, HttpRouteValueDictionary matchedValues)
{
if (String.IsNullOrEmpty(requestPathSegment))
{
// If there's no data to parse, we must have exactly one parameter segment and no other segments - otherwise no match
if (routeSegment.Subsegments.Count > 1)
{
return false;
}
PathParameterSubsegment parameterSubsegment = routeSegment.Subsegments[0] as PathParameterSubsegment;
if (parameterSubsegment == null)
{
return false;
}
// We must have a default value since there's no value in the request URI
object parameterValue;
if (defaultValues.TryGetValue(parameterSubsegment.ParameterName, out parameterValue))
{
// If there's a default value for this parameter, use that default value
matchedValues.Add(parameterSubsegment.ParameterName, parameterValue);
return true;
}
else
{
// If there's no default value, this segment doesn't match
return false;
}
}
// Find last literal segment and get its last index in the string
int lastIndex = requestPathSegment.Length;
int indexOfLastSegmentUsed = routeSegment.Subsegments.Count - 1;
PathParameterSubsegment parameterNeedsValue = null; // Keeps track of a parameter segment that is pending a value
PathLiteralSubsegment lastLiteral = null; // Keeps track of the left-most literal we've encountered
while (indexOfLastSegmentUsed >= 0)
{
int newLastIndex = lastIndex;
PathParameterSubsegment parameterSubsegment = routeSegment.Subsegments[indexOfLastSegmentUsed] as PathParameterSubsegment;
if (parameterSubsegment != null)
{
// Hold on to the parameter so that we can fill it in when we locate the next literal
parameterNeedsValue = parameterSubsegment;
}
else
{
PathLiteralSubsegment literalSubsegment = routeSegment.Subsegments[indexOfLastSegmentUsed] as PathLiteralSubsegment;
if (literalSubsegment != null)
{
lastLiteral = literalSubsegment;
int startIndex = lastIndex - 1;
// If we have a pending parameter subsegment, we must leave at least one character for that
if (parameterNeedsValue != null)
{
startIndex--;
}
if (startIndex < 0)
{
return false;
}
int indexOfLiteral = requestPathSegment.LastIndexOf(literalSubsegment.Literal, startIndex, StringComparison.OrdinalIgnoreCase);
if (indexOfLiteral == -1)
{
// If we couldn't find this literal index, this segment cannot match
return false;
}
// If the first subsegment is a literal, it must match at the right-most extent of the request URI.
// Without this check if your route had "/Foo/" we'd match the request URI "/somethingFoo/".
// This check is related to the check we do at the very end of this function.
if (indexOfLastSegmentUsed == (routeSegment.Subsegments.Count - 1))
{
if ((indexOfLiteral + literalSubsegment.Literal.Length) != requestPathSegment.Length)
{
return false;
}
}
newLastIndex = indexOfLiteral;
}
else
{
Contract.Assert(false, "Invalid path segment type");
}
}
if ((parameterNeedsValue != null) && (((lastLiteral != null) && (parameterSubsegment == null)) || (indexOfLastSegmentUsed == 0)))
{
// If we have a pending parameter that needs a value, grab that value
int parameterStartIndex;
//.........这里部分代码省略.........
示例7: MatchCatchAll
private static void MatchCatchAll(PathContentSegment contentPathSegment, IEnumerable<string> remainingRequestSegments, HttpRouteValueDictionary defaultValues, HttpRouteValueDictionary matchedValues)
{
string remainingRequest = String.Join(String.Empty, remainingRequestSegments.ToArray());
PathParameterSubsegment catchAllSegment = contentPathSegment.Subsegments[0] as PathParameterSubsegment;
object catchAllValue;
if (remainingRequest.Length > 0)
{
catchAllValue = remainingRequest;
}
else
{
defaultValues.TryGetValue(catchAllSegment.ParameterName, out catchAllValue);
}
matchedValues.Add(catchAllSegment.ParameterName, catchAllValue);
}
示例8: Match
public HttpRouteValueDictionary Match(string virtualPath, HttpRouteValueDictionary defaultValues)
{
IList<string> requestPathSegments = HttpRouteParser.SplitUriToPathSegmentStrings(virtualPath);
if (defaultValues == null)
{
defaultValues = new HttpRouteValueDictionary();
}
HttpRouteValueDictionary matchedValues = new HttpRouteValueDictionary();
// This flag gets set once all the data in the URI has been parsed through, but
// the route we're trying to match against still has more parts. At this point
// we'll only continue matching separator characters and parameters that have
// default values.
bool ranOutOfStuffToParse = false;
// This value gets set once we start processing a catchall parameter (if there is one
// at all). Once we set this value we consume all remaining parts of the URI into its
// parameter value.
bool usedCatchAllParameter = false;
for (int i = 0; i < _pathSegments.Count; i++)
{
PathSegment pathSegment = _pathSegments[i];
if (requestPathSegments.Count <= i)
{
ranOutOfStuffToParse = true;
}
string requestPathSegment = ranOutOfStuffToParse ? null : requestPathSegments[i];
if (pathSegment is PathSeparatorSegment)
{
if (ranOutOfStuffToParse)
{
// If we're trying to match a separator in the route but there's no more content, that's OK
}
else
{
if (!String.Equals(requestPathSegment, "/", StringComparison.Ordinal))
{
return null;
}
}
}
else
{
PathContentSegment contentPathSegment = pathSegment as PathContentSegment;
if (contentPathSegment != null)
{
if (contentPathSegment.IsCatchAll)
{
Contract.Assert(i == (_pathSegments.Count - 1), "If we're processing a catch-all, we should be on the last route segment.");
MatchCatchAll(contentPathSegment, requestPathSegments.Skip(i), defaultValues, matchedValues);
usedCatchAllParameter = true;
}
else
{
if (!MatchContentPathSegment(contentPathSegment, requestPathSegment, defaultValues, matchedValues))
{
return null;
}
}
}
else
{
Contract.Assert(false, "Invalid path segment type");
}
}
}
if (!usedCatchAllParameter)
{
if (_pathSegments.Count < requestPathSegments.Count)
{
// If we've already gone through all the parts defined in the route but the URI
// still contains more content, check that the remaining content is all separators.
for (int i = _pathSegments.Count; i < requestPathSegments.Count; i++)
{
if (!HttpRouteParser.IsSeparator(requestPathSegments[i]))
{
return null;
}
}
}
}
// Copy all remaining default values to the route data
if (defaultValues != null)
{
foreach (var defaultValue in defaultValues)
{
if (!matchedValues.ContainsKey(defaultValue.Key))
{
matchedValues.Add(defaultValue.Key, defaultValue.Value);
}
}
}
//.........这里部分代码省略.........
示例9: Bind
public BoundRouteTemplate Bind(IDictionary<string, object> currentValues, IDictionary<string, object> values, HttpRouteValueDictionary defaultValues, HttpRouteValueDictionary constraints)
{
if (currentValues == null)
{
currentValues = new HttpRouteValueDictionary();
}
if (values == null)
{
values = new HttpRouteValueDictionary();
}
if (defaultValues == null)
{
defaultValues = new HttpRouteValueDictionary();
}
// The set of values we should be using when generating the URI in this route
HttpRouteValueDictionary acceptedValues = new HttpRouteValueDictionary();
// Keep track of which new values have been used
HashSet<string> unusedNewValues = new HashSet<string>(values.Keys, StringComparer.OrdinalIgnoreCase);
// Step 1: Get the list of values we're going to try to use to match and generate this URI
// Find out which entries in the URI are valid for the URI we want to generate.
// If the URI had ordered parameters a="1", b="2", c="3" and the new values
// specified that b="9", then we need to invalidate everything after it. The new
// values should then be a="1", b="9", c=<no value>.
ForEachParameter(_pathSegments, delegate(PathParameterSubsegment parameterSubsegment)
{
// If it's a parameter subsegment, examine the current value to see if it matches the new value
string parameterName = parameterSubsegment.ParameterName;
object newParameterValue;
bool hasNewParameterValue = values.TryGetValue(parameterName, out newParameterValue);
if (hasNewParameterValue)
{
unusedNewValues.Remove(parameterName);
}
object currentParameterValue;
bool hasCurrentParameterValue = currentValues.TryGetValue(parameterName, out currentParameterValue);
if (hasNewParameterValue && hasCurrentParameterValue)
{
if (!RoutePartsEqual(currentParameterValue, newParameterValue))
{
// Stop copying current values when we find one that doesn't match
return false;
}
}
// If the parameter is a match, add it to the list of values we will use for URI generation
if (hasNewParameterValue)
{
if (IsRoutePartNonEmpty(newParameterValue))
{
acceptedValues.Add(parameterName, newParameterValue);
}
}
else
{
if (hasCurrentParameterValue)
{
acceptedValues.Add(parameterName, currentParameterValue);
}
}
return true;
});
// Add all remaining new values to the list of values we will use for URI generation
foreach (var newValue in values)
{
if (IsRoutePartNonEmpty(newValue.Value))
{
if (!acceptedValues.ContainsKey(newValue.Key))
{
acceptedValues.Add(newValue.Key, newValue.Value);
}
}
}
// Add all current values that aren't in the URI at all
foreach (var currentValue in currentValues)
{
string parameterName = currentValue.Key;
if (!acceptedValues.ContainsKey(parameterName))
{
PathParameterSubsegment parameterSubsegment = GetParameterSubsegment(_pathSegments, parameterName);
if (parameterSubsegment == null)
{
acceptedValues.Add(parameterName, currentValue.Value);
}
}
}
// Add all remaining default values from the route to the list of values we will use for URI generation
ForEachParameter(_pathSegments, delegate(PathParameterSubsegment parameterSubsegment)
{
//.........这里部分代码省略.........
示例10: GetHttpRouteHelper
private static string GetHttpRouteHelper(HttpRequestMessage request, string routeName, IDictionary<string, object> routeValues)
{
if (routeValues == null)
{
// If no route values were passed in at all we have to create a new dictionary
// so that we can add the extra "httproute" key.
routeValues = new HttpRouteValueDictionary();
routeValues.Add(HttpRoute.HttpRouteKey, true);
}
else
{
// Copy the dictionary so that we can guarantee that routeValues uses an OrdinalIgnoreCase comparer
// and to add the extra "httproute" key used by all Web API routes to disambiguate them from other MVC routes.
routeValues = new HttpRouteValueDictionary(routeValues);
if (!routeValues.ContainsKey(HttpRoute.HttpRouteKey))
{
routeValues.Add(HttpRoute.HttpRouteKey, true);
}
}
HttpConfiguration configuration = request.GetConfiguration();
if (configuration == null)
{
throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoConfiguration);
}
IHttpVirtualPathData vpd = configuration.Routes.GetVirtualPath(
request: request,
name: routeName,
values: routeValues);
if (vpd == null)
{
return null;
}
return vpd.VirtualPath;
}
示例11: MatchSingleContentPathSegment
private static bool MatchSingleContentPathSegment(PathSubsegment pathSubsegment, string requestPathSegment, HttpRouteValueDictionary matchedValues)
{
PathParameterSubsegment parameterSubsegment = pathSubsegment as PathParameterSubsegment;
if (parameterSubsegment == null)
{
// Handle a single literal segment
PathLiteralSubsegment literalSubsegment = pathSubsegment as PathLiteralSubsegment;
Contract.Assert(literalSubsegment != null, "Invalid path segment type");
return literalSubsegment.Literal.Equals(requestPathSegment, StringComparison.OrdinalIgnoreCase);
}
else
{
// Handle a single parameter segment
matchedValues.Add(parameterSubsegment.ParameterName, requestPathSegment);
return true;
}
}
示例12: BuildHttpRouteValueDictionary
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;
}
示例13: BuildHttpRoute
/// <summary>
/// Builds an <see cref="IHttpRoute"/> for a particular action.
/// </summary>
/// <param name="routeTemplate">The tokenized route template for the route.</param>
/// <param name="httpMethods">The HTTP methods supported by the route.</param>
/// <param name="controllerName">The name of the associated controller.</param>
/// <param name="actionName">The name of the associated action.</param>
/// <returns>The generated <see cref="IHttpRoute"/>.</returns>
public virtual IHttpRoute BuildHttpRoute(string routeTemplate, IEnumerable<HttpMethod> httpMethods, string controllerName, string actionName)
{
if (routeTemplate == null)
{
throw Error.ArgumentNull("routeTemplate");
}
if (controllerName == null)
{
throw Error.ArgumentNull("controllerName");
}
if (actionName == null)
{
throw Error.ArgumentNull("actionName");
}
HttpRouteValueDictionary defaults = new HttpRouteValueDictionary
{
{ "controller", controllerName },
{ "action", actionName }
};
HttpRouteValueDictionary constraints = new HttpRouteValueDictionary();
if (httpMethods != null)
{
// Current method constraint implementation is inefficient since it matches before running the constraint.
// Consider checking the HTTP method first in a custom route as a performance optimization.
constraints.Add("httpMethod", new HttpMethodConstraint(httpMethods.ToArray()));
}
string detokenizedRouteTemplate = ParseRouteTemplate(routeTemplate, defaults, constraints);
return BuildHttpRoute(defaults, constraints, detokenizedRouteTemplate);
}
示例14: ParseRouteTemplate
private string ParseRouteTemplate(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints)
{
Contract.Assert(defaults != null);
Contract.Assert(constraints != null);
MatchCollection parameterMatches = _parameterRegex.Matches(routeTemplate);
foreach (Match parameterMatch in parameterMatches)
{
string parameterName = parameterMatch.Groups["parameterName"].Value;
// We may need to strip out the initial wildcard used for wildcard parameters
if (parameterName.StartsWith("*", StringComparison.OrdinalIgnoreCase))
{
parameterName = parameterName.Substring(1);
}
// Add the default value if present
Group defaultValueGroup = parameterMatch.Groups["defaultValue"];
object defaultValue = GetDefaultValue(defaultValueGroup);
if (defaultValue != null)
{
defaults.Add(parameterName, defaultValue);
}
// Register inline constraints if present
Group constraintGroup = parameterMatch.Groups["constraint"];
bool isOptional = defaultValue == RouteParameter.Optional;
IHttpRouteConstraint constraint = GetInlineConstraint(constraintGroup, isOptional);
if (constraint != null)
{
constraints.Add(parameterName, constraint);
}
}
// Replaces parameter matches with just the parameter name in braces
// Strips out the optional '?', default value, inline constraints
return _parameterRegex.Replace(routeTemplate, @"{${parameterName}}");
}
示例15: CreateRoute_ValidatesConstraintType_InvalidType
public void CreateRoute_ValidatesConstraintType_InvalidType()
{
// Arrange
var routes = new HttpRouteCollection();
var constraint = new Uri("http://localhost/");
var constraints = new HttpRouteValueDictionary();
constraints.Add("custom", constraint);
string expectedMessage =
"The constraint entry 'custom' on the route with route template '{controller}/{id}' " +
"must have a string value or be of a type which implements 'System.Web.Http.Routing.IHttpRouteConstraint'.";
// Act & Assert
Assert.Throws<InvalidOperationException>(() => routes.CreateRoute("{controller}/{id}", null, constraints), expectedMessage);
}