Skip to content

Commit

Permalink
First commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
Aaron Roney authored and Aaron Roney committed Oct 5, 2017
0 parents commit 68d7fd8
Show file tree
Hide file tree
Showing 6 changed files with 260 additions and 0 deletions.
32 changes: 32 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# User-specific files
*.suo
*.user
*.sln.docstates

.vs/
.vscode/

appsettings.json
package.sh

# Build results

[Dd]ebug/
[Rr]elease/
x64/
build/
[Bb]in/
[Oo]bj/

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
13 changes: 13 additions & 0 deletions AspNetCore.Proxy.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Version>1.0.2</Version>
<AssemblyName>AspNetCore.Proxy</AssemblyName>
<PackageId>AspNetCore.Proxy</PackageId>
<DocumentationFile>bin\AspNetCore.Proxy.xml</DocumentationFile>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="2.0.0" />
</ItemGroup>
</Project>
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2017 Aaron Roney

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.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# AspNetCore.Proxy

ASP.NET Core Proxies made easy.

## Information

### Install

```bash
dotnet add AspNetCore.Proxy
```

### Compatibility

Latest .NET Standard 2.0.

### Examples

## License

```
The MIT License (MIT)
Copyright (c) 2016 Aaron Roney
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.
```
121 changes: 121 additions & 0 deletions src/Helpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyModel;

namespace AspNetCore.Proxy
{
public static class Helpers
{
public static IEnumerable<Assembly> GetReferencingAssemblies()
{
var assemblies = new List<Assembly>();
var dependencies = DependencyContext.Default.RuntimeLibraries;
foreach (var library in dependencies)
{
var assembly = Assembly.Load(new AssemblyName(library.Name));
assemblies.Add(assembly);
}
return assemblies;
}
}

public static class Extensions
{
public static HttpRequestMessage CreateProxyHttpRequest(this HttpContext context, string uriString)
{
var uri = new Uri(uriString);
var request = context.Request;

var requestMessage = new HttpRequestMessage();
var requestMethod = request.Method;
if (!HttpMethods.IsGet(requestMethod) &&
!HttpMethods.IsHead(requestMethod) &&
!HttpMethods.IsDelete(requestMethod) &&
!HttpMethods.IsTrace(requestMethod))
{
var streamContent = new StreamContent(request.Body);
requestMessage.Content = streamContent;
}

// Copy the request headers
foreach (var header in request.Headers)
{
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
}
}

requestMessage.Headers.Host = uri.Authority;
requestMessage.RequestUri = uri;
requestMessage.Method = new HttpMethod(request.Method);

return requestMessage;
}

public static Task<HttpResponseMessage> SendProxyHttpRequest(this HttpContext context, string proxiedAddress)
{
var proxiedRequest = context.CreateProxyHttpRequest(proxiedAddress);
return new HttpClient().SendAsync(proxiedRequest, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted);
}

public static async Task CopyProxyHttpResponse(this HttpContext context, HttpResponseMessage responseMessage)
{
var response = context.Response;

response.StatusCode = (int)responseMessage.StatusCode;
foreach (var header in responseMessage.Headers)
{
response.Headers[header.Key] = header.Value.ToArray();
}

foreach (var header in responseMessage.Content.Headers)
{
response.Headers[header.Key] = header.Value.ToArray();
}

response.Headers.Remove("transfer-encoding");

using (var responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
await responseStream.CopyToAsync(response.Body, 81920, context.RequestAborted);
}
}

public static void UseProxy(this IApplicationBuilder app, string endpoint, Func<IDictionary<string, object>, Task<string>> getProxiedAddress, Func<HttpContext, Exception, Task> onFailure = null)
{
app.UseRouter(builder => {
builder.MapMiddlewareRoute(endpoint, proxyApp => {
proxyApp.Run(async context => {
try
{
var proxiedAddress = await getProxiedAddress(context.GetRouteData().Values.ToDictionary(v => v.Key, v => v.Value));
var proxiedResponse = await context.SendProxyHttpRequest(proxiedAddress);
await context.CopyProxyHttpResponse(proxiedResponse);
}
catch(Exception e)
{
if(onFailure == null)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync($"Request could not be proxied.\n\n{e.Message}\n\n{e.StackTrace}.");
return;
}
await onFailure(context, e);
}
});
});
});
}
}
}
44 changes: 44 additions & 0 deletions src/ProxyRouteAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyModel;

namespace AspNetCore.Proxy
{
[AttributeUsage(AttributeTargets.Method)]
public class ProxyRouteAttribute : Attribute
{
public string Route { get; set; }

public ProxyRouteAttribute(string route)
{
Route = route;
}
}

public static class ProxyExtensions
{
public static void UseProxies(this IApplicationBuilder app)
{
var methods = Helpers.GetReferencingAssemblies().SelectMany(a => a.GetTypes()).SelectMany(t => t.GetMethods()).Where(m => m.GetCustomAttributes(typeof(ProxyRouteAttribute), false).Length > 0);

foreach(var method in methods)
{
var attribute = method.GetCustomAttributes(typeof(ProxyRouteAttribute), false).First() as ProxyRouteAttribute;
var parameters = method.GetParameters();
var instance = Activator.CreateInstance(method.DeclaringType);

if(!(method.ReturnType == typeof(Task<string>)))
throw new Exception("Proxied methods must return a Task<string>.");

app.UseProxy(attribute.Route, args => {
if(args.Count() != parameters.Count())
throw new Exception("Parameter mismatch.");
return method.Invoke(instance, args.Select(kvp => kvp.Value).ToArray()) as Task<string>;
});
}
}
}
}

0 comments on commit 68d7fd8

Please sign in to comment.