Added some wrapper around the http context so i can at least pretend to access things from it without casting them

This commit is contained in:
TomPallister
2016-10-05 20:46:00 +01:00
parent ab8407e7dc
commit 229c0878ed
9 changed files with 208 additions and 32 deletions

View File

@ -0,0 +1,11 @@
using Ocelot.Library.Infrastructure.Responses;
namespace Ocelot.Library.Infrastructure.Services
{
public class CannotAddDataError : Error
{
public CannotAddDataError(string message) : base(message)
{
}
}
}

View File

@ -0,0 +1,11 @@
using Ocelot.Library.Infrastructure.Responses;
namespace Ocelot.Library.Infrastructure.Services
{
public class CannotFindDataError : Error
{
public CannotFindDataError(string message) : base(message)
{
}
}
}

View File

@ -0,0 +1,10 @@
using Ocelot.Library.Infrastructure.Responses;
namespace Ocelot.Library.Infrastructure.Services
{
public interface IRequestDataService
{
Response Add<T>(string key, T value);
Response<T> Get<T>(string key);
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Ocelot.Library.Infrastructure.Responses;
namespace Ocelot.Library.Infrastructure.Services
{
public class RequestDataService : IRequestDataService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public RequestDataService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public Response Add<T>(string key, T value)
{
try
{
_httpContextAccessor.HttpContext.Items.Add(key, value);
return new OkResponse();
}
catch (Exception exception)
{
return new ErrorResponse(new List<Error>
{
new CannotAddDataError(string.Format($"Unable to add data for key: {key}, exception: {exception.Message}"))
});
}
}
public Response<T> Get<T>(string key)
{
object obj;
if(_httpContextAccessor.HttpContext.Items.TryGetValue(key, out obj))
{
var data = (T) obj;
return new OkResponse<T>(data);
}
return new ErrorResponse<T>(new List<Error>
{
new CannotFindDataError($"Unable to find data for key: {key}")
});
}
}
}