How to write a ServiceStack plugin which needs both request and response Dtos

老子叫甜甜 提交于 2019-12-04 07:53:47
Andreas Niedermair

First off: Why do you need the request itself, when all you need is the value of the Language property?

The following code is a legit solution for your scenario:

public class LocalizationFeature : IPlugin
{
  public const string LanguageKey = "X-Language";

  public void Register(IAppHost appHost)
  {
    this.GlobalRequestFilters.Add(this.InterceptRequest);
    this.GlobalResponseFilters.Add(this.InterceptResponse);
  }

  private void InterceptRequest(IRequest request,
                                IResponse response,
                                object dto)
  {
    var localizedRequest = dto as ILocalizedRequest;
    if (localizedRequest != null)
    {
      request.SetItem(LanguageKey,
                      localizedRequest.Language);
    }
  }

  private void InterceptResponse(IRequest request,
                                 IResponse response,
                                 object dto)
  {
    var localizedDto = dto as ILocalizedDto;
    if (localizedDto != null)
    {
      var language = request.GetParam(LanguageKey) ?? request.GetItem(LanguageKey);
      if (!string.IsNullOrEmpty(language))
      {
        Localizer.Translate(localizedDto,
                            language);
      }
    }
  }
}

The interesting thing here is var language = request.GetParam(LanguageKey) ?? request.GetItem(LanguageKey);, which gives you the opportunity to inject the language with either an HTTP header, cookie, or form-data (if applicable) with the key "X-Language". (You could also do another ?? DefaultLanguage to inject a default language for translating ...)

If it is not supplied this way, the set Language of the request is read from the Items of the request and used.

Edit: Additionally, as pointed out by @mythz, you can also access the request DTO with request.Dto in the InterceptResponse method:

private void InterceptResponse(IRequest request,
                               IResponse response,
                               object dto)
{
    var localizedRequest = request.Dto as ILocalizedRequest;
    var localizedDto = dto as ILocalizedDto;
    if (localizedRequest != null
        && localizedDto != null)
    {
      Localizer.Translate(localizedDto,
                          localizedRequest.Language);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!