Reputation: 455
I want merge two routes Get["/"]
and Get["/{value:int}"]
.
How?
Get["/{value?:int}"]
and Get["/{value:int?}"]
returns 404 error.
Upvotes: 1
Views: 2977
Reputation:
I found that you can assign the same method for multiple GET definitions (or any HTTP verb):
Get["/"] = Get["/{value:int}"] = _ => { // method here }
The final result is the same, althought not an elegant one.
Upvotes: 3
Reputation: 13137
I had a look at the Nancy source code (2014/05/20) and it doesn't look like it's built to handle optional values on the route constraints.
The following code segment from the CaptureNodeWithConstraint class seems to do the constrain'ed segment matching. It does a basic split on the ':' character to separate the parameter name and the constraint:
/// <summary>
/// Matches the segment for a requested route
/// </summary>
/// <param name="segment">Segment string</param>
/// <returns>A <see cref="SegmentMatch"/> instance representing the result of the match</returns>
public override SegmentMatch Match(string segment)
{
var routeSegmentConstraint = routeSegmentConstraints.FirstOrDefault(x => x.Matches(constraint));
if (routeSegmentConstraint == null)
{
return SegmentMatch.NoMatch;
}
return routeSegmentConstraint.GetMatch(this.constraint, segment, this.parameterName);
}
private void ExtractParameterName()
{
var segmentSplit = this.RouteDefinitionSegment.Trim('{', '}').Split(':');
this.parameterName = segmentSplit[0];
this.constraint = segmentSplit[1];
}
This then farms off to the GetMatch(,,,) methods of the constraints, which as far as I can see have nothing within to allow for an optional parameter.
I tried creating your route using various forms of regular expression based routes, like:
Get[@"/(?<value>[\d]{0,3})"] = parameters => "Hello World";
And a greedy regular expression:
Get[@"^(?<value>[\d]{0,3})$"] = parameters => "Hello World";
But all of these gave me 404 for the '/' route.
I am guessing this cannot be done using the standard routing definitions. You may have to do a basic optional route like so:
Get[@"/{value?}"] = parameters => "Hello World";
And then add the validation of the 'value' parameter within your handler.
Upvotes: 2