made a response middlware as terminating middleware...

This commit is contained in:
TomPallister
2016-10-08 09:59:37 +01:00
parent 3685efec05
commit a7a1143823
17 changed files with 165 additions and 86 deletions

View File

@ -3,13 +3,14 @@ using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Ocelot.Library.Infrastructure.RequestBuilder
{
public class RequestBuilder : IRequestBuilder
public class HttpRequestBuilder : IRequestBuilder
{
public Request Build(string httpMethod, string downstreamUrl, Stream content, IHeaderDictionary headers,
public async Task<Request> Build(string httpMethod, string downstreamUrl, Stream content, IHeaderDictionary headers,
IRequestCookieCollection cookies, string queryString, string contentType)
{
var method = new HttpMethod(httpMethod);
@ -20,7 +21,11 @@ namespace Ocelot.Library.Infrastructure.RequestBuilder
if (content != null)
{
httpRequestMessage.Content = new StreamContent(content);
using (var reader = new StreamReader(content))
{
var body = await reader.ReadToEndAsync();
httpRequestMessage.Content = new StringContent(body);
}
}
if (!string.IsNullOrEmpty(contentType))
@ -41,7 +46,11 @@ namespace Ocelot.Library.Infrastructure.RequestBuilder
{
foreach (var header in headers)
{
httpRequestMessage.Headers.Add(header.Key, header.Value.ToArray());
//todo get rid of if..
if (header.Key.ToLower() != "host")
{
httpRequestMessage.Headers.Add(header.Key, header.Value.ToArray());
}
}
}

View File

@ -1,11 +1,12 @@
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Ocelot.Library.Infrastructure.RequestBuilder
{
public interface IRequestBuilder
{
Request Build(string httpMethod,
Task<Request> Build(string httpMethod,
string downstreamUrl,
Stream content,
IHeaderDictionary headers,

View File

@ -1,17 +1,32 @@
using System.Net.Http;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Ocelot.Library.Infrastructure.RequestBuilder;
using Ocelot.Library.Infrastructure.Responses;
namespace Ocelot.Library.Infrastructure.Requester
{
public class HttpClientHttpRequester : IHttpRequester
{
public async Task<HttpResponseMessage> GetResponse(Request request)
public async Task<Response<HttpResponseMessage>> GetResponse(Request request)
{
using (var handler = new HttpClientHandler { CookieContainer = request.CookieContainer })
using (var httpClient = new HttpClient(handler))
{
return await httpClient.SendAsync(request.HttpRequestMessage);
try
{
var response = await httpClient.SendAsync(request.HttpRequestMessage);
return new OkResponse<HttpResponseMessage>(response);
}
catch (Exception exception)
{
return
new ErrorResponse<HttpResponseMessage>(new List<Error>
{
new UnableToCompleteRequestError(exception)
});
}
}
}
}

View File

@ -1,11 +1,12 @@
using System.Net.Http;
using System.Threading.Tasks;
using Ocelot.Library.Infrastructure.RequestBuilder;
using Ocelot.Library.Infrastructure.Responses;
namespace Ocelot.Library.Infrastructure.Requester
{
public interface IHttpRequester
{
Task<HttpResponseMessage> GetResponse(Request request);
Task<Response<HttpResponseMessage>> GetResponse(Request request);
}
}

View File

@ -0,0 +1,13 @@
using System;
using Ocelot.Library.Infrastructure.Responses;
namespace Ocelot.Library.Infrastructure.Requester
{
public class UnableToCompleteRequestError : Error
{
public UnableToCompleteRequestError(Exception exception)
: base($"Error making http request, exception: {exception.Message}")
{
}
}
}

View File

@ -11,7 +11,12 @@ namespace Ocelot.Library.Infrastructure.Responder
{
if (response.IsSuccessStatusCode)
{
context.Response.StatusCode = (int)response.StatusCode;
context.Response.OnStarting(x =>
{
context.Response.StatusCode = (int)response.StatusCode;
return Task.CompletedTask;
}, context);
await context.Response.WriteAsync(await response.Content.ReadAsStringAsync());
return context;
}
@ -20,7 +25,11 @@ namespace Ocelot.Library.Infrastructure.Responder
public async Task<HttpContext> CreateNotFoundResponse(HttpContext context)
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
context.Response.OnStarting(x =>
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return Task.CompletedTask;
}, context);
return context;
}
}

View File

@ -2,6 +2,6 @@ namespace Ocelot.Library.Infrastructure.UrlMatcher
{
public interface IUrlPathToUrlTemplateMatcher
{
UrlMatch Match(string upstreamUrlPath, string upstreamUrlTemplate);
UrlMatch Match(string upstreamUrlPath, string upstreamUrlPathTemplate);
}
}

View File

@ -5,21 +5,26 @@ namespace Ocelot.Library.Infrastructure.UrlMatcher
{
public class UrlPathToUrlTemplateMatcher : IUrlPathToUrlTemplateMatcher
{
public UrlMatch Match(string upstreamUrlPath, string upstreamUrlTemplate)
public UrlMatch Match(string upstreamUrlPath, string upstreamUrlPathTemplate)
{
var urlPathTemplateCopy = upstreamUrlTemplate;
if (upstreamUrlPath.Length > upstreamUrlPathTemplate.Length)
{
return new UrlMatch(false, new List<TemplateVariableNameAndValue>(), string.Empty);
}
var urlPathTemplateCopy = upstreamUrlPathTemplate;
var templateKeysAndValues = new List<TemplateVariableNameAndValue>();
int counterForUrl = 0;
for (int counterForTemplate = 0; counterForTemplate < upstreamUrlTemplate.Length; counterForTemplate++)
for (int counterForTemplate = 0; counterForTemplate < upstreamUrlPathTemplate.Length; counterForTemplate++)
{
if (CharactersDontMatch(upstreamUrlTemplate[counterForTemplate], upstreamUrlPath[counterForUrl]) && ContinueScanningUrl(counterForUrl,upstreamUrlPath.Length))
if (CharactersDontMatch(upstreamUrlPathTemplate[counterForTemplate], upstreamUrlPath[counterForUrl]) && ContinueScanningUrl(counterForUrl,upstreamUrlPath.Length))
{
if (IsPlaceholder(upstreamUrlTemplate[counterForTemplate]))
if (IsPlaceholder(upstreamUrlPathTemplate[counterForTemplate]))
{
var variableName = GetPlaceholderVariableName(upstreamUrlTemplate, counterForTemplate);
var variableName = GetPlaceholderVariableName(upstreamUrlPathTemplate, counterForTemplate);
var variableValue = GetPlaceholderVariableValue(upstreamUrlPath, counterForUrl);
@ -27,7 +32,7 @@ namespace Ocelot.Library.Infrastructure.UrlMatcher
templateKeysAndValues.Add(templateVariableNameAndValue);
counterForTemplate = GetNextCounterPosition(upstreamUrlTemplate, counterForTemplate, '}');
counterForTemplate = GetNextCounterPosition(upstreamUrlPathTemplate, counterForTemplate, '}');
counterForUrl = GetNextCounterPosition(upstreamUrlPath, counterForUrl, '/');

View File

@ -36,7 +36,7 @@ namespace Ocelot.Library.Middleware
return;
}
var request = _requestBuilder
var request = await _requestBuilder
.Build(context.Request.Method, downstreamUrl.Data, context.Request.Body,
context.Request.Headers, context.Request.Cookies, context.Request.QueryString.Value, context.Request.ContentType);

View File

@ -1,3 +1,4 @@
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Ocelot.Library.Infrastructure.Repository;
@ -14,19 +15,16 @@ namespace Ocelot.Library.Middleware
private readonly IHttpRequester _requester;
private readonly IHttpResponder _responder;
private readonly IScopedRequestDataRepository _scopedRequestDataRepository;
private readonly IRequestBuilder _requestBuilder;
public HttpRequesterMiddleware(RequestDelegate next,
IHttpRequester requester,
IHttpResponder responder,
IScopedRequestDataRepository scopedRequestDataRepository,
IRequestBuilder requestBuilder)
IScopedRequestDataRepository scopedRequestDataRepository)
{
_next = next;
_requester = requester;
_responder = responder;
_scopedRequestDataRepository = scopedRequestDataRepository;
_requestBuilder = requestBuilder;
}
public async Task Invoke(HttpContext context)
@ -42,8 +40,8 @@ namespace Ocelot.Library.Middleware
var response = await _requester
.GetResponse(request.Data);
await _responder.CreateResponse(context, response);
_scopedRequestDataRepository.Add("Response", response.Data);
await _next.Invoke(context);
}
}

View File

@ -0,0 +1,34 @@
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Ocelot.Library.Infrastructure.Repository;
using Ocelot.Library.Infrastructure.Responder;
namespace Ocelot.Library.Middleware
{
/// <summary>
/// Terminating middleware that is responsible for returning a http response to the client
/// </summary>
public class HttpResponderMiddleware
{
private readonly RequestDelegate _next;
private readonly IHttpResponder _responder;
private readonly IScopedRequestDataRepository _scopedRequestDataRepository;
public HttpResponderMiddleware(RequestDelegate next,
IHttpResponder responder,
IScopedRequestDataRepository scopedRequestDataRepository)
{
_next = next;
_responder = responder;
_scopedRequestDataRepository = scopedRequestDataRepository;
}
public async Task Invoke(HttpContext context)
{
var response = _scopedRequestDataRepository.Get<HttpResponseMessage>("Response");
await _responder.CreateResponse(context, response.Data);
}
}
}

View File

@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Builder;
namespace Ocelot.Library.Middleware
{
public static class HttpResponderMiddlewareExtensions
{
public static IApplicationBuilder UseHttpResponderMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HttpResponderMiddleware>();
}
}
}

View File

@ -1,10 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
namespace Ocelot
{

View File

@ -44,7 +44,7 @@ namespace Ocelot
services.AddSingleton<IDownstreamRouteFinder, DownstreamRouteFinder>();
services.AddSingleton<IHttpRequester, HttpClientHttpRequester>();
services.AddSingleton<IHttpResponder, HttpContextResponder>();
services.AddSingleton<IRequestBuilder, RequestBuilder>();
services.AddSingleton<IRequestBuilder, HttpRequestBuilder>();
// see this for why we register this as singleton http://stackoverflow.com/questions/37371264/invalidoperationexception-unable-to-resolve-service-for-type-microsoft-aspnetc
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
@ -65,6 +65,8 @@ namespace Ocelot
app.UseHttpRequestBuilderMiddleware();
app.UseHttpRequesterMiddleware();
app.UseHttpResponderMiddleware();
}
}
}

View File

@ -1,4 +1,4 @@
ReRoutes:
- DownstreamTemplate: http://www.bbc.co.uk
- DownstreamTemplate: http://www.mattsite.dev/
UpstreamTemplate: /
UpstreamHttpMethod: Get