我正在将数据从移动设备发布到Web API。发布请求JSON包含图片,因此我已将base64string转换为Web API上的发布。我正在GZIP中转换JSON。以下是我用于将请求从移动设备发送到XAMARIN FORM PCL
var jsonPictures = JsonConvert.SerializeObject(dataOrderPictures);
using (HttpClientHandler ClientHandler = new HttpClientHandler())
using (HttpClient Client = new HttpClient(ClientHandler))
{
Client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
var content = new StringContent(jsonPictures, Encoding.UTF8, "application/json");
var result1 = await Client.PostAsync(uri, content);
var enc = Encoding.UTF8;
using (Stream responseStream = result1.Content.ReadAsStreamAsync().Result)
{
using (var decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress))
{
using (var rd = new StreamReader(decompressedStream, enc))
{
pictureResult = rd.ReadToEnd();
}
}
}
下面是Web API代码:
[HttpPost]
[CompressFilter]
public HttpResponseMessage SavePictures1(int driverid, string pswd, JObject jsonResult)
{
var rawMessage = Request.Content.ReadAsByteArrayAsync();
}
CompressFilter类:
public class CompressFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actContext)
{
var content = actContext.Response.Content;
var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
var zlibbedContent = bytes == null ? new byte[0] :
CompressionHelper.DeflateByte(bytes);
actContext.Response.Content = new ByteArrayContent(zlibbedContent);
actContext.Response.Content.Headers.Remove("Content-Type");
actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
actContext.Response.Content.Headers.Add("Content-Type", "application/json");
base.OnActionExecuted(actContext);
}
}
public class CompressionHelper
{
public static byte[] DeflateByte(byte[] str)
{
if (str == null)
{ return null; }
ErrorLog.WriteAPIRequest("", "Driver", Convert.ToString(str.Length), "SavePictures", "Test");
using (var output = new MemoryStream())
{
using (var compressor = new Ionic.Zlib.GZipStream( output, Ionic.Zlib.CompressionMode.Compress,Ionic.Zlib.CompressionLevel.BestSpeed))
{
compressor.Write(str, 0, str.Length);
}
return output.ToArray();
}
}
}
我想检查我从手机发送的请求内容长度。如何在上面的Web Api代码中获取内容长度。所以我可以检查GZip是否正常工作,以及实际JSON和GZIP有什么区别。希望有人可以帮助得到这个。