Skip to content

Commit 21c7b9c

Browse files
committed
Recurse LoadDocument on redirects
1 parent 3d4b1a7 commit 21c7b9c

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/json-ld.net/Core/DocumentLoader.cs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,13 @@ public virtual RemoteDocument LoadDocument(string url)
1616
{
1717
#if !PORTABLE && !IS_CORECLR
1818
RemoteDocument doc = new RemoteDocument(url, null);
19+
HttpWebResponse resp;
20+
1921
try
2022
{
2123
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
2224
req.Accept = AcceptHeader;
23-
WebResponse resp = req.GetResponse();
25+
resp = (HttpWebResponse)req.GetResponse();
2426
bool isJsonld = resp.Headers[HttpResponseHeader.ContentType] == "application/ld+json";
2527
if (!resp.Headers[HttpResponseHeader.ContentType].Contains("json"))
2628
{
@@ -31,7 +33,7 @@ public virtual RemoteDocument LoadDocument(string url)
3133
if (!isJsonld && linkHeaders != null)
3234
{
3335
linkHeaders = linkHeaders.SelectMany((h) => h.Split(",".ToCharArray()))
34-
.Select(h => h.Trim()).ToArray();
36+
.Select(h => h.Trim()).ToArray();
3537
IEnumerable<string> linkedContexts = linkHeaders.Where(v => v.EndsWith("rel=\"http://www.w3.org/ns/json-ld#context\""));
3638
if (linkedContexts.Count() > 1)
3739
{
@@ -54,6 +56,29 @@ public virtual RemoteDocument LoadDocument(string url)
5456
{
5557
throw;
5658
}
59+
catch (WebException webException)
60+
{
61+
try
62+
{
63+
resp = (HttpWebResponse)webException.Response;
64+
int baseStatusCode = (int)(Math.Floor((double)resp.StatusCode / 100)) * 100;
65+
if (baseStatusCode == 300)
66+
{
67+
string location = resp.Headers[HttpResponseHeader.Location];
68+
if (!string.IsNullOrWhiteSpace(location))
69+
{
70+
// TODO: Add recursion break or simply switch to HttpClient so we don't have to recurse on HTTP redirects.
71+
return LoadDocument(location);
72+
}
73+
}
74+
}
75+
catch (Exception innerException)
76+
{
77+
throw new JsonLdError(JsonLdError.Error.LoadingDocumentFailed, url, innerException);
78+
}
79+
80+
throw new JsonLdError(JsonLdError.Error.LoadingDocumentFailed, url, webException);
81+
}
5782
catch (Exception exception)
5883
{
5984
throw new JsonLdError(JsonLdError.Error.LoadingDocumentFailed, url, exception);

0 commit comments

Comments
 (0)