【问题标题】:ServiceStack - As passthru to another ServiceStack serviceServiceStack - 作为另一个 ServiceStack 服务的通路
【发布时间】:2016-09-16 16:18:36
【问题描述】:

我目前有一个 ServiceStack 服务,它只是将请求中继到内部 ServiceStack 服务。

中继服务是这样设置的(代码以简短为例):

public class RelayService : Service
{
    public SomeDTO Get(FetchSomething request)
    {
        try
        {
            return new JsonServiceClient(settings.OtherServiceURL).Get(request);
        }
        catch (Exception)
        {
            throw;
        }
    }

    public void Put(PersistSomething request)
    {
        try
        {
            new JsonServiceClient(settings.OtherServiceURL).Put(request);
        }
        catch (Exception)
        {
            throw;
        }
    }
}

我的问题是:

  1. 最佳实践是为每个请求新建一个 JsonServiceClient 吗?还是应该注入一个实例?

  2. 由于中继服务可以包含返回 DTO 或 void 的 Put/Get 变体,是否有更简洁的方法将所有调用中继到后备 ServiceStack 服务,而不必复制中继服务中的每个方法?是否可以使用 Any() 以一种或几种方法完成所有这些操作?

感谢您的任何意见。

【问题讨论】:

    标签: c# servicestack


    【解决方案1】:

    上一个答案是 ServiceStack 中 generic reverse proxy 的示例。

    ServiceStack 中最简单和最通用的方法是注册一个RawHttpHandler,它只是将请求转发到下游服务器并将响应写入输出流,例如:

    RawHttpHandlers.Add(_ => new CustomActionHandler((req, res) =>
    {
        var bytes = req.InputStream.ReadFully();
        var proxyUrl = settings.OtherServiceURL.CombineWith(req.RawUrl);
        var responseBytes = proxyUrl.SendBytesToUrl(method: req.Verb,
            requestBody: bytes,
            accept:MimeTypes.Json,
            contentType: req.ContentType, 
            responseFilter: webRes =>
            {
                res.StatusCode = (int)webRes.StatusCode;
                res.StatusDescription = webRes.StatusDescription;
                res.ContentType = webRes.ContentType;
            });
    
        res.OutputStream.Write(responseBytes, 0, responseBytes.Length);
    }));
    

    为了访问 RequestStream,您还需要告诉 ServiceStack 在创建请求时不要检查 FormData(因为这会强制读取请求正文),您可以跳过:

    SetConfig(new HostConfig { 
        SkipFormDataInCreatingRequest = true
    });
    

    另一种方法是配置 IIS Application Request Routing and URL Rewriting 之类的东西以用作反向代理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      相关资源
      最近更新 更多