-
Notifications
You must be signed in to change notification settings - Fork 931
Expand file tree
/
Copy pathRequestHeaderRouteValueTransform.cs
More file actions
62 lines (52 loc) · 1.94 KB
/
Copy pathRequestHeaderRouteValueTransform.cs
File metadata and controls
62 lines (52 loc) · 1.94 KB
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
53
54
55
56
57
58
59
60
61
62
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
namespace Yarp.ReverseProxy.Transforms;
public class RequestHeaderRouteValueTransform : RequestHeaderTransform
{
public RequestHeaderRouteValueTransform(string headerName, string routeValueKey, bool append)
: base(headerName, append)
{
if (string.IsNullOrEmpty(headerName))
{
throw new ArgumentException($"'{nameof(headerName)}' cannot be null or empty.", nameof(headerName));
}
if (string.IsNullOrEmpty(routeValueKey))
{
throw new ArgumentException($"'{nameof(routeValueKey)}' cannot be null or empty.", nameof(routeValueKey));
}
RouteValueKey = routeValueKey;
}
internal string RouteValueKey { get; }
protected override string? GetValue(RequestTransformContext context)
{
var routeValues = context.HttpContext.Request.RouteValues;
if (!routeValues.TryGetValue(RouteValueKey, out var value))
{
return null;
}
return value?.ToString();
}
internal override void ApplyFast(HttpContext httpContext, HttpRequestMessage proxyRequest, ref bool headersCopied)
{
if (!httpContext.Request.RouteValues.TryGetValue(RouteValueKey, out var routeValue)
|| routeValue?.ToString() is not { } value)
{
return;
}
if (Append)
{
var existingValues = TakeHeader(httpContext, proxyRequest, headersCopied, HeaderName);
AddHeader(proxyRequest, HeaderName, StringValues.Concat(existingValues, value));
}
else
{
RemoveHeader(proxyRequest, HeaderName);
AddHeader(proxyRequest, HeaderName, value);
}
}
}