Last active
April 5, 2024 20:53
-
-
Save pimbrouwers/8f78e318ccfefff18f518a483997be29 to your computer and use it in GitHub Desktop.
C# Parse Link Header
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
public class LinkHeader | |
{ | |
public string FirstLink { get; set; } | |
public string PrevLink { get; set; } | |
public string NextLink { get; set; } | |
public string LastLink { get; set; } | |
public static LinkHeader LinksFromHeader(string linkHeaderStr) | |
{ | |
LinkHeader linkHeader = null; | |
if (!string.IsNullOrWhiteSpace(linkHeaderStr)) | |
{ | |
string[] linkStrings = linkHeaderStr.Split(','); | |
if (linkStrings != null && linkStrings.Any()) | |
{ | |
linkHeader = new LinkHeader(); | |
foreach (string linkString in linkStrings) | |
{ | |
var relMatch = Regex.Match(linkString, "(?<=rel=\").+?(?=\")", RegexOptions.IgnoreCase); | |
var linkMatch = Regex.Match(linkString, "(?<=<).+?(?=>)", RegexOptions.IgnoreCase); | |
if (relMatch.Success && linkMatch.Success) | |
{ | |
string rel = relMatch.Value.ToUpper(); | |
string link = linkMatch.Value; | |
switch (rel) | |
{ | |
case "FIRST": | |
linkHeader.FirstLink = link; | |
break; | |
case "PREV": | |
linkHeader.PrevLink = link; | |
break; | |
case "NEXT": | |
linkHeader.NextLink = link; | |
break; | |
case "LAST": | |
linkHeader.LastLink = link; | |
break; | |
} | |
} | |
} | |
} | |
} | |
return linkHeader; | |
} | |
} |
Works great, thanks!
Is there a JS/TS equivalent to this? If not, could someone please help me with writing this?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this breaks if the URL's themselves have commas in them. A more robust solution is here: https://stackoverflow.com/a/72034960