Repository: andychiare/netcore2-reverse-proxy
Branch: master
Commit: 197d20144220
Files: 10
Total size: 11.8 KB
Directory structure:
gitextract_a85h9ktw/
├── .gitignore
├── LICENSE
├── README.md
├── ReverseProxyApplication/
│ ├── Program.cs
│ ├── Properties/
│ │ └── launchSettings.json
│ ├── ReverseProxyApplication.csproj
│ ├── ReverseProxyApplication.csproj.user
│ ├── ReverseProxyMiddleware.cs
│ └── Startup.cs
└── ReverseProxyApplication.sln
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
/ReverseProxyApplication/bin
/ReverseProxyApplication/obj
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2018 Andrea Chiarelli
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# netcore2-reverse-proxy
This is a .NET Core 2 sample project showing how to implement a custom reverse proxy, as described in the article [Building a Reverse Proxy in .NET Core](https://auth0.com/blog/building-a-reverse-proxy-in-dot-net-core/).
## Running the project ##
You can run the Web application from Visual Studio or by typing `dotnet run` in a command window.
When the application is running, you can point your browser to `localhost:5001` and access a Google form without leaving the `localhost` domain.
================================================
FILE: ReverseProxyApplication/Program.cs
================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace ReverseProxyApplication
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
================================================
FILE: ReverseProxyApplication/Properties/launchSettings.json
================================================
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57068",
"sslPort": 44388
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ReverseProxyApplication": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
================================================
FILE: ReverseProxyApplication/ReverseProxyApplication.csproj
================================================
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
</ItemGroup>
</Project>
================================================
FILE: ReverseProxyApplication/ReverseProxyApplication.csproj.user
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup>
<ActiveDebugProfile>ReverseProxyApplication</ActiveDebugProfile>
</PropertyGroup>
</Project>
================================================
FILE: ReverseProxyApplication/ReverseProxyMiddleware.cs
================================================
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ReverseProxyApplication
{
public class ReverseProxyMiddleware
{
private static readonly HttpClient _httpClient = new HttpClient();
private readonly RequestDelegate _nextMiddleware;
public ReverseProxyMiddleware(RequestDelegate nextMiddleware)
{
_nextMiddleware = nextMiddleware;
}
public async Task Invoke(HttpContext context)
{
var targetUri = BuildTargetUri(context.Request);
if (targetUri != null)
{
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
context.Response.StatusCode = (int)responseMessage.StatusCode;
CopyFromTargetResponseHeaders(context, responseMessage);
await ProcessResponseContent(context, responseMessage);
}
return;
}
await _nextMiddleware(context);
}
private async Task ProcessResponseContent(HttpContext context, HttpResponseMessage responseMessage)
{
var content = await responseMessage.Content.ReadAsByteArrayAsync();
if (IsContentOfType(responseMessage, "text/html") || IsContentOfType(responseMessage, "text/javascript"))
{
var stringContent = Encoding.UTF8.GetString(content);
var newContent = stringContent.Replace("https://www.google.com", "/google")
.Replace("https://www.gstatic.com", "/googlestatic")
.Replace("https://docs.google.com/forms", "/googleforms");
await context.Response.WriteAsync(newContent, Encoding.UTF8);
} else
{
await context.Response.Body.WriteAsync(content);
}
}
private bool IsContentOfType(HttpResponseMessage responseMessage, string type)
{
var result = false;
if (responseMessage.Content?.Headers?.ContentType != null)
{
result = responseMessage.Content.Headers.ContentType.MediaType == type;
}
return result;
}
private HttpRequestMessage CreateTargetMessage(HttpContext context, Uri targetUri)
{
var requestMessage = new HttpRequestMessage();
CopyFromOriginalRequestContentAndHeaders(context, requestMessage);
targetUri = new Uri(QueryHelpers.AddQueryString(targetUri.OriginalString, new Dictionary<string, string>() { { "entry.1884265043", "John Doe" }}));
requestMessage.RequestUri = targetUri;
requestMessage.Headers.Host = targetUri.Host;
requestMessage.Method = GetMethod(context.Request.Method);
return requestMessage;
}
private void CopyFromOriginalRequestContentAndHeaders(HttpContext context, HttpRequestMessage requestMessage)
{
var requestMethod = context.Request.Method;
if (!HttpMethods.IsGet(requestMethod) &&
!HttpMethods.IsHead(requestMethod) &&
!HttpMethods.IsDelete(requestMethod) &&
!HttpMethods.IsTrace(requestMethod))
{
var streamContent = new StreamContent(context.Request.Body);
requestMessage.Content = streamContent;
}
foreach (var header in context.Request.Headers)
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
}
}
private void CopyFromTargetResponseHeaders(HttpContext context, HttpResponseMessage responseMessage)
{
foreach (var header in responseMessage.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
foreach (var header in responseMessage.Content.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
context.Response.Headers.Remove("transfer-encoding");
}
private static HttpMethod GetMethod(string method)
{
if (HttpMethods.IsDelete(method)) return HttpMethod.Delete;
if (HttpMethods.IsGet(method)) return HttpMethod.Get;
if (HttpMethods.IsHead(method)) return HttpMethod.Head;
if (HttpMethods.IsOptions(method)) return HttpMethod.Options;
if (HttpMethods.IsPost(method)) return HttpMethod.Post;
if (HttpMethods.IsPut(method)) return HttpMethod.Put;
if (HttpMethods.IsTrace(method)) return HttpMethod.Trace;
return new HttpMethod(method);
}
private Uri BuildTargetUri(HttpRequest request)
{
Uri targetUri = null;
PathString remainingPath;
if (request.Path.StartsWithSegments("/googleforms", out remainingPath))
{
targetUri = new Uri("https://docs.google.com/forms" + remainingPath);
}
if (request.Path.StartsWithSegments("/google", out remainingPath))
{
targetUri = new Uri("https://www.google.com" + remainingPath);
}
if (request.Path.StartsWithSegments("/googlestatic", out remainingPath))
{
targetUri = new Uri(" https://www.gstatic.com" + remainingPath);
}
return targetUri;
}
}
}
================================================
FILE: ReverseProxyApplication/Startup.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace ReverseProxyApplication
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware<ReverseProxyMiddleware>();
app.Run(async (context) =>
{
await context.Response.WriteAsync("<a href='/googleforms/d/e/1FAIpQLSdJwmxHIl_OCh-CI1J68G1EVSr9hKaYFLh3dHh8TLnxjxCJWw/viewform?hl=en'>Register to receive a T-shirt</a>");
});
}
}
}
================================================
FILE: ReverseProxyApplication.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.136
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReverseProxyApplication", "ReverseProxyApplication\ReverseProxyApplication.csproj", "{58B4515A-294E-4C42-A583-77EC95AFF5DA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{58B4515A-294E-4C42-A583-77EC95AFF5DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{58B4515A-294E-4C42-A583-77EC95AFF5DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{58B4515A-294E-4C42-A583-77EC95AFF5DA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{58B4515A-294E-4C42-A583-77EC95AFF5DA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CE1981AA-AB03-4074-B464-1A50E3CF42DE}
EndGlobalSection
EndGlobal
gitextract_a85h9ktw/ ├── .gitignore ├── LICENSE ├── README.md ├── ReverseProxyApplication/ │ ├── Program.cs │ ├── Properties/ │ │ └── launchSettings.json │ ├── ReverseProxyApplication.csproj │ ├── ReverseProxyApplication.csproj.user │ ├── ReverseProxyMiddleware.cs │ └── Startup.cs └── ReverseProxyApplication.sln
SYMBOL INDEX (16 symbols across 3 files)
FILE: ReverseProxyApplication/Program.cs
class Program (line 13) | public class Program
method Main (line 15) | public static void Main(string[] args)
method CreateWebHostBuilder (line 20) | public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
FILE: ReverseProxyApplication/ReverseProxyMiddleware.cs
class ReverseProxyMiddleware (line 14) | public class ReverseProxyMiddleware
method ReverseProxyMiddleware (line 19) | public ReverseProxyMiddleware(RequestDelegate nextMiddleware)
method Invoke (line 24) | public async Task Invoke(HttpContext context)
method ProcessResponseContent (line 47) | private async Task ProcessResponseContent(HttpContext context, HttpRes...
method IsContentOfType (line 64) | private bool IsContentOfType(HttpResponseMessage responseMessage, stri...
method CreateTargetMessage (line 76) | private HttpRequestMessage CreateTargetMessage(HttpContext context, Ur...
method CopyFromOriginalRequestContentAndHeaders (line 90) | private void CopyFromOriginalRequestContentAndHeaders(HttpContext cont...
method CopyFromTargetResponseHeaders (line 109) | private void CopyFromTargetResponseHeaders(HttpContext context, HttpRe...
method GetMethod (line 122) | private static HttpMethod GetMethod(string method)
method BuildTargetUri (line 134) | private Uri BuildTargetUri(HttpRequest request)
FILE: ReverseProxyApplication/Startup.cs
class Startup (line 12) | public class Startup
method ConfigureServices (line 16) | public void ConfigureServices(IServiceCollection services)
method Configure (line 21) | public void Configure(IApplicationBuilder app, IHostingEnvironment env)
Condensed preview — 10 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (13K chars).
[
{
"path": ".gitignore",
"chars": 58,
"preview": "/ReverseProxyApplication/bin\n/ReverseProxyApplication/obj\n"
},
{
"path": "LICENSE",
"chars": 1073,
"preview": "MIT License\n\nCopyright (c) 2018 Andrea Chiarelli\n\nPermission is hereby granted, free of charge, to any person obtaining "
},
{
"path": "README.md",
"chars": 520,
"preview": "# netcore2-reverse-proxy\nThis is a .NET Core 2 sample project showing how to implement a custom reverse proxy, as descri"
},
{
"path": "ReverseProxyApplication/Program.cs",
"chars": 619,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing"
},
{
"path": "ReverseProxyApplication/Properties/launchSettings.json",
"chars": 662,
"preview": "{\n \"iisSettings\": {\n \"windowsAuthentication\": false, \n \"anonymousAuthentication\": true, \n \"iisExpress\": {\n "
},
{
"path": "ReverseProxyApplication/ReverseProxyApplication.csproj",
"chars": 400,
"preview": "<Project Sdk=\"Microsoft.NET.Sdk.Web\">\n\n <PropertyGroup>\n <TargetFramework>netcoreapp2.1</TargetFramework>\n </Proper"
},
{
"path": "ReverseProxyApplication/ReverseProxyApplication.csproj.user",
"chars": 395,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbui"
},
{
"path": "ReverseProxyApplication/ReverseProxyMiddleware.cs",
"chars": 5940,
"preview": "using Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.WebUtilities;\nusing Microsoft.Extensions.Primitives;\nusing "
},
{
"path": "ReverseProxyApplication/Startup.cs",
"chars": 1275,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.AspNet"
},
{
"path": "ReverseProxyApplication.sln",
"chars": 1140,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 15\nVisualStudioVersion = 15.0.28307.136\nMi"
}
]
About this extraction
This page contains the full source code of the andychiare/netcore2-reverse-proxy GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 10 files (11.8 KB), approximately 2.8k tokens, and a symbol index with 16 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.