blob: 7b8f0ec9f1fd094076837c36282ecb71c2cda497 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
using System;
using System.Net;
using Microsoft.AspNetCore.Rewrite;
namespace StardewModdingAPI.Web.Framework.RedirectRules
{
/// <summary>Redirect hostnames to a URL if they match a condition.</summary>
internal class RedirectHostsToUrlsRule : RedirectMatchRule
{
/*********
** Fields
*********/
/// <summary>Maps a lowercase hostname to the resulting redirect URL.</summary>
private readonly Func<string, string?> Map;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="statusCode">The status code to use for redirects.</param>
/// <param name="map">Hostnames mapped to the resulting redirect URL.</param>
public RedirectHostsToUrlsRule(HttpStatusCode statusCode, Func<string, string?> map)
{
this.StatusCode = statusCode;
this.Map = map ?? throw new ArgumentNullException(nameof(map));
}
/*********
** Private methods
*********/
/// <summary>Get the new redirect URL.</summary>
/// <param name="context">The rewrite context.</param>
/// <returns>Returns the redirect URL, or <c>null</c> if the redirect doesn't apply.</returns>
protected override string? GetNewUrl(RewriteContext context)
{
// get requested host
string? host = context.HttpContext.Request.Host.Host;
// get new host
host = this.Map(host);
if (host == null)
return null;
// rewrite URL
UriBuilder uri = this.GetUrl(context.HttpContext.Request);
uri.Host = host;
return uri.ToString();
}
}
}
|