ServiceStack intercept requests before they are sent client side

送分小仙女□ 提交于 2019-12-25 03:36:32

问题


I have implemented a custom HMAC authentication for servicestack (example shown here). As suggested at the bottom of the link, I wanted to do something like this client side:

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);
        };

which appends the authentication headers for every request sent to the API from this client. However LocalHttpWebRequestFilter doesn't seem to be a property of JsonServiceClient anymore. Is there an alternative to achieve this?


回答1:


I found a solution for this. Instead of using LocalHttpWebRequestFilter, need to just use RequestFilter. The final solution looks like this:

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);
    };

Credit for the solution here: ServiceStack JsonServiceClient - Custom HTTP Headers not sent



来源:https://stackoverflow.com/questions/30347698/servicestack-intercept-requests-before-they-are-sent-client-side

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!