ServiceStack在客户端发送之前拦截请求

时间:2015-05-20 10:58:58

标签: servicestack

我已经为servicestack实现了自定义HMAC身份验证(示例显示为here)。正如链接底部的建议,我想做这样的客户端:

var client = new JsonServiceClient();

client.LocalHttpWebRequestFilter +=
    delegate(HttpWebRequest request)
        {
            // ContentType still null at this point so we must hard code it
            // Set these fields before trying to create the token!
            request.ContentType = ServiceStack.Common.Web.ContentType.Json;
            request.Date = DateTime.Now;

            var secret = "5771CC06-B86D-41A6-AB39-9CA2BA338E27";
            var token = ApiSignature.CreateToken(request, secret);
            request.Headers.Add(ApiCustomHttpHeaders.UserId, "1");
            request.Headers.Add(ApiCustomHttpHeaders.Signature, token);
        };

为每个从此客户端发送到API的请求附加身份验证标头。但是,LocalHttpWebRequestFilter似乎不再是JsonServiceClient的属性。有没有替代方法来实现这个目标?

1 个答案:

答案 0 :(得分:2)

我找到了解决方案。不要使用LocalHttpWebRequestFilter,而只需使用RequestFilter。最终解决方案如下所示:

var client = new JsonServiceClient();

client.RequestFilter +=
  delegate(HttpWebRequest request)
    {
        // ContentType still null at this point so we must hard code it
        // Set these fields before trying to create the token!
        request.ContentType = ServiceStack.Common.Web.ContentType.Json;
        request.Date = DateTime.Now;

        var secret = "5771CC06-B86D-41A6-AB39-9CA2BA338E27";
        var token = ApiSignature.CreateToken(request, secret);
        request.Headers.Add(ApiCustomHttpHeaders.UserId, "1");
        request.Headers.Add(ApiCustomHttpHeaders.Signature, token);
    };

此处解决方案:ServiceStack JsonServiceClient - Custom HTTP Headers not sent