ServiceStack客户端压缩

时间:2017-01-02 14:43:52

标签: servicestack

我想压缩客户端发送的请求。

我找到了Q / A: ServiceStack - How To Compress Requests From Client

但是当使用这段代码时,我从服务器得到一个SerializationException,内容应该以'{'开头而不是'\ u001F ...'

此解决方案是否仍然有效或是否有其他方法来压缩客户端请求有效负载?

更新1:这是Fiddler的输出。请求:

POST http://xxxxxx:8104/entries HTTP/1.1
Accept: application/json
User-Agent: ServiceStack .NET Client 4,51
Accept-Encoding: gzip,deflate
Content-Encoding: gzip
Content-Type: application/json
Host: xxxxxx:8104
Content-Length: 187
Expect: 100-continue

[binary data not shown here]

回复:

HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Tue, 03 Jan 2017 07:22:57 GMT

427
{"ResponseStatus":{"ErrorCode":"SerializationException","Message":"Could not deserialize 'application/json' request using Namespace.NameOfDto'\nError: System.Runtime.Serialization.SerializationException: Type definitions should start with a '{', expecting serialized type 'NameOfDto', got string starting with: \u001F \b\u0000\u0000\u0000\u0000\u0000\u0004\u00005  \n @\u0010  e 1 P W :h\u001D :D M'YЙ \u001D B| F   7 \r\n   at ServiceStack.Text.Common.DeserializeTypeRefJson.StringToType(TypeConfig typeConfig, String strType, EmptyCtorDelegate ctorFn, Dictionary`2 typeAccessorMap)\r\n   at ServiceStack.Text.Common.DeserializeType`1.<>c__DisplayClass1_0.<GetParseMethod>b__1(String value)\r\n   at ServiceStack.Text.JsonSerializer.DeserializeFromString(String value, Type type)\r\n   at ServiceStack.Text.JsonSerializer.DeserializeFromStream(Type type, Stream stream)\r\n   at ServiceStack.Serialization.JsonDataContractSerializer.DeserializeFromStream(Type type, S
27e
tream stream)\r\n   at ServiceStack.Host.Handlers.ServiceStackHandlerBase.CreateContentTypeRequest(IRequest httpReq, Type requestType, String contentType)","StackTrace":"   at ServiceStack.Host.Handlers.ServiceStackHandlerBase.CreateContentTypeRequest(IRequest httpReq, Type requestType, String contentType)\r\n   at ServiceStack.Host.RestHandler.CreateRequest(IRequest httpReq, IRestPath restPath, Dictionary`2 requestParams)\r\n   at ServiceStack.Host.RestHandler.CreateRequest(IRequest httpReq, IRestPath restPath)\r\n   at ServiceStack.Host.RestHandler.ProcessRequestAsync(IRequest httpReq, IResponse httpRes, String operationName)"}}
0

客户端:

public class GzipJsonServiceClient : JsonServiceClient
{
    public GzipJsonServiceClient()
    {
        SetRequestFilter();
    }

    public GzipJsonServiceClient(string baseUri)
        : base(baseUri)
    {
        SetRequestFilter();
    }

    public override void SerializeToStream(IRequest requestContext, object request, Stream stream)
    {
        using (var gzipStream = new GZipStream(stream, CompressionMode.Compress))
        {
            base.SerializeToStream(requestContext, request, gzipStream);
            gzipStream.Close();
        }
    }

    private void SetRequestFilter()
    {
        RequestFilter = req =>
        {
            if (req.Method.HasRequestBody())
            {
                req.Headers.Add(HttpRequestHeader.ContentEncoding, CompressionTypes.GZip);
            }
        };
    }
}

请求代码:

var client = new GzipJsonServiceClient(uri) { Timeout = TimeSpan.FromSeconds(10) };
var request = new NameOfDto();
client.Post(request);

服务端来自Visual Studio模板,在Windows服务中托管ServiceStack服务。它很香草,有一种方法没有达到:

public void Post(NameOfDto request)
{
    var appHost = (AppHost)HostContext.AppHost;
    ...
}

2 个答案:

答案 0 :(得分:1)

ServiceStack HttpListener Server和this commit中的所有C#服务客户端都添加了对客户端Gzip + Deflate压缩的支持。

这使您可以使用新的RequestCompressionType属性发送客户端请求,例如:

var client = new JsonServiceClient(baseUrl)
{
    RequestCompressionType = CompressionTypes.GZip,
};

var response = client.Post(new NameOfDto { ... });

此功能适用于v4.5.5 +,现在为available on MyGet

答案 1 :(得分:0)

好的,所以我想出了一种方法来解决我的问题,使用Newtonsoft JSON nuget。虽然我更愿意,如果有一个开箱即用的#34;使用ServiceStack的解决方案,我没有必要修改DTO。

我将IRequiresRequestStream接口添加到我的DTO:

[Route("/entries", "POST")]
public class NameOfDto : IRequiresRequestStream
{
    [ApiMember(IsRequired = true)]
    public string OneOfManyProperties { get; set; }

    public Stream RequestStream { get; set; }
}

然后创建了新类:

public static class GZipRequestStreamParser
{
    public static T ParseRequestStream<T>(Stream requestStream)
    {
        using (var gzipStream = new GZipStream(requestStream, CompressionMode.Decompress))
        using (var reader = new StreamReader(gzipStream))
        {
            var serializedObject = reader.ReadToEnd();
            var deserializedObject = JsonConvert.DeserializeObject<T>(serializedObject);
            return deserializedObject;
        }
    }
}

最后更新了终点:

public void Post(NameOfDto request)
{
    request = GZipRequestStreamParser.ParseRequestStream<NameOfDto>(request.RequestStream);

    var appHost = (AppHost)HostContext.AppHost;

    // work with request object!
}