Created
May 10, 2014 02:42
-
-
Save garethj-msft/33035a364ddc2c59911a to your computer and use it in GitHub Desktop.
PathHandler to support more traditional URI route conventions for id references for ODataControllers for V4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Path handler to switch to using segment notation for collection IDs | |
/// </summary> | |
internal class SegmentIdPathHandler : DefaultODataPathHandler | |
{ | |
/// <summary> | |
/// Handle URI's using either ID format on the way in to the API | |
/// </summary> | |
protected override ODataPathSegment ParseAtCollection(IEdmModel model, ODataPathSegment previous, IEdmType previousEdmType, string segment, Queue<string> segments) | |
{ | |
ODataPathSegment retVal = null; | |
try | |
{ | |
// If this looks like a custom id. | |
if (previousEdmType.TypeKind == EdmTypeKind.Collection && segment[0] != '(') | |
{ | |
// We allow string ids to index collections as keys, so try forming it up as an index. | |
retVal = base.ParseAtCollection(model, previous, previousEdmType, "(" + segment + ")", segments); | |
} | |
else // Just use regular parsing. | |
{ | |
retVal = base.ParseAtCollection(model, previous, previousEdmType, segment, segments); | |
} | |
} | |
catch (ODataException) // Fall back to default parsing if we guessed wrong. | |
{ | |
retVal = base.ParseAtCollection(model, previous, previousEdmType, segment, segments); | |
} | |
return retVal; | |
} | |
/// <summary> | |
/// Make IDs serialize as segments on the way out of the API. | |
/// </summary> | |
public override string Link(ODataPath path) | |
{ | |
var stringBuilder = new StringBuilder(); | |
bool flag = true; | |
foreach (ODataPathSegment odataPathSegment in path.Segments) | |
{ | |
if (odataPathSegment != null) | |
{ | |
if (!flag) | |
{ | |
stringBuilder.Append('/'); | |
} | |
if (odataPathSegment is KeyValuePathSegment) | |
{ | |
// Don't use quotes around ids. | |
var kvSegment = (KeyValuePathSegment)odataPathSegment; | |
stringBuilder.Append(kvSegment.Value.Trim('\'')); | |
} | |
else | |
{ | |
stringBuilder.Append(odataPathSegment.ToString()); | |
} | |
flag = false; | |
} | |
} | |
return ((object)stringBuilder).ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment