Last active
October 20, 2016 02:07
-
-
Save ronnieoverby/96ee9c98a66611cc0d555b9b898b53b3 to your computer and use it in GitHub Desktop.
It's REALLY easy to create a Reverse HTTP Server with Web API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void SetupRouting(HttpConfiguration config) | |
{ | |
config.Routes.MapHttpRoute("proxy_else", "{*uri}", new | |
{ | |
controller = "Proxy", | |
uri = RouteParameter.Optional | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net.Http; | |
using System.Threading.Tasks; | |
using System.Web.Http; | |
using System; | |
using System.Configuration; | |
namespace MyApp.Controllers | |
{ | |
public class ProxyController : ApiController | |
{ | |
readonly HttpClient _client = new HttpClient(); | |
[HttpGet, HttpPost, HttpPut, HttpDelete, HttpPatch, HttpHead, HttpOptions] | |
public async Task<IHttpActionResult> HandleRequest() | |
{ | |
Request.RequestUri = TransformUri(Request.RequestUri); | |
if (Request.Method == HttpMethod.Get || Request.Method == HttpMethod.Head) | |
Request.Content = null; | |
var response = await _client.SendAsync(Request); | |
return ResponseMessage(response); | |
} | |
protected override void Dispose(bool disposing) | |
{ | |
using (_client) | |
base.Dispose(disposing); | |
} | |
private Uri TransformUri(Uri requestUri) | |
{ | |
var ub = new UriBuilder(requestUri); | |
ub.Host = ProxiedUri.Host; | |
ub.Port = ProxiedUri.Port; | |
return ub.Uri; | |
} | |
private static readonly Uri ProxiedUri = new Uri(ConfigurationManager.AppSettings["ProxiedUrl"]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment