I need to serve localized data. All response Dtos that are localized have the same properties. That is, I defined an interface ( ILocalizedDto) to mark these Dtos. On the request side, there is a request ILocalizedRequestfor requests requiring localization.
Using IPlugin, I have already managed to implement the required function. However, I am sure that the implementation is not thread safe, and in addition, I do not know if I can use IHttpRequest.GetHashCode () as an identifier for one request / response cycle.
What would be the correct way to implement the ServiceStack plugin that uses both the request and the Dto response? That is, is there some kind of IHttpRequest.Context for storing data, or can I get a dto request during the response?
internal class LocalizationFeature : IPlugin
{
public static bool Enabled { private set; get; }
public void Register(IAppHost appHost)
{
if (Enabled)
{
return;
}
Enabled = true;
var filter = new LocalizationFilter();
appHost.RequestFilters.Add(filter.RequestFilter);
appHost.ResponseFilters.Add(filter.ResponseFilter);
}
}
public class LocalizationFilter
{
private readonly Dictionary<int,ILocalizedRequest> localizedRequests = new Dictionary<int, ILocalizedRequest>();
public ILocalizer Localizer { get; set; }
public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
{
var localizedRequest = requestDto as ILocalizedRequest;
if (localizedRequest != null)
{
localizedRequests.Add(GetRequestId(req), localizedRequest);
}
}
public void ResponseFilter(IHttpRequest req, IHttpResponse res, object response)
{
var requestId = GetRequestId(req);
if (!(response is ILocalizedDto) || !localizedRequests.ContainsKey(requestId))
{
return;
}
var localizedDto = response as ILocalizedDto;
var localizedRequest = localizedRequests[requestId];
localizedRequests.Remove(requestId);
Localizer.Translate(localizedDto, localizedRequest.Language);
}
private static int GetRequestId(IHttpRequest req)
{
return req.GetHashCode();
}
}
source
share