Fix master server

This commit is contained in:
Sardelka 2022-07-11 13:26:28 +08:00
parent a9397690e2
commit 89410b8b46
2 changed files with 62 additions and 2 deletions

View File

@ -141,7 +141,6 @@ namespace RageCoop.Server
Logger?.Error(ex.InnerException?.Message ?? ex.Message); Logger?.Error(ex.InnerException?.Message ?? ex.Message);
return; return;
} }
var realMaster = Settings.MasterServer;
while (!_stopping) while (!_stopping)
{ {
string msg = string msg =
@ -161,7 +160,8 @@ namespace RageCoop.Server
HttpResponseMessage response = null; HttpResponseMessage response = null;
try try
{ {
response = await httpClient.PostAsync(realMaster, new StringContent(msg, Encoding.UTF8, "application/json")); var realUrl = Util.GetFinalRedirect(Settings.MasterServer);
response = await httpClient.PostAsync(realUrl, new StringContent(msg, Encoding.UTF8, "application/json"));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -103,5 +103,65 @@ namespace RageCoop.Server
{ {
return values[new Random().Next(values.Length-1)]; return values[new Random().Next(values.Length-1)];
} }
public static string GetFinalRedirect(string url)
{
if (string.IsNullOrWhiteSpace(url))
return url;
int maxRedirCount = 8; // prevent infinite loops
string newUrl = url;
do
{
HttpWebRequest req = null;
HttpWebResponse resp = null;
try
{
req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "HEAD";
req.AllowAutoRedirect = false;
resp = (HttpWebResponse)req.GetResponse();
switch (resp.StatusCode)
{
case HttpStatusCode.OK:
return newUrl;
case HttpStatusCode.Redirect:
case HttpStatusCode.MovedPermanently:
case HttpStatusCode.RedirectKeepVerb:
case HttpStatusCode.RedirectMethod:
newUrl = resp.Headers["Location"];
if (newUrl == null)
return url;
if (newUrl.IndexOf("://", System.StringComparison.Ordinal) == -1)
{
// Doesn't have a URL Schema, meaning it's a relative or absolute URL
Uri u = new Uri(new Uri(url), newUrl);
newUrl = u.ToString();
}
break;
default:
return newUrl;
}
url = newUrl;
}
catch (WebException)
{
// Return the last known good URL
return newUrl;
}
catch
{
return null;
}
finally
{
if (resp != null)
resp.Close();
}
} while (maxRedirCount-- > 0);
return newUrl;
}
} }
} }