使用ReadAsAsync和WriteToStreamAsync的WebApi Formatter - 当xml工作正常时Json被截断

时间:2016-10-19 10:23:55

标签: c# json xml asp.net-web-api response

我正在使用C#WebAPI 2并获得一种奇怪的行为。

我有调用Controller的服务,有时可以发送内容作为Json和其他用作调用的XML机制的内容如下:

using (var client = new HttpClient())
{
    var pricingControllerUrl = CreateEndpoint(apiUrl);
    using (var response = (int)request.Metadata.InputType >= 3 ?  client.PostAsJsonAsync(pricingControllerUrl, request) : client.PostAsXmlWithSerializerAsync(pricingControllerUrl, request))
    {
        if (response.Result.IsSuccessStatusCode)
        {
            var session = response.Result.Content.ReadAsAsync<Session>(new List<MediaTypeFormatter>() { new XmlMediaTypeFormatter { UseXmlSerializer = true }, new JsonMediaTypeFormatter() }).Result;
            return session;
        }
    }
}

public static class HttpExtensions
{
    public static Task<HttpResponseMessage> PostAsXmlWithSerializerAsync<T>(this HttpClient client, string requestUri, T value)
    {
        return client.PostAsync(new Uri(requestUri), value,
                      new XmlMediaTypeFormatter { UseXmlSerializer = true }
                      );
    }
}

在接收端(控制器),

public async Task<IHttpActionResult> PostSession([FromBody] Session session)
    {
    //do the calculations
    return Content(HttpStatusCode.OK, sessionResponse, new ReducedSessionFormatter(), this.Request.Content.Headers.ContentType);
    }

必须通过在调度之前删除一些信息来减少响应,下面的格式化程序用于促进这一点:

public class ReducedSessionFormatter : MediaTypeFormatter
{
    public ReducedSessionFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
    }

    public ReducedSessionFormatter(MediaTypeFormatter formatter) : base(formatter)
    {
    }

    public override bool CanReadType(Type type)
    {
        return false;
    }

    public override bool CanWriteType(Type type)
    {
        return type.IsAssignableFrom(typeof (Session));
    }

    protected XDocument ReduceXml(XDocument doc)
    {

        //removing stuff from xml
        return doc;
    }

    protected JObject ReduceJson(JObject serializedJson)
    {
        //removing stuff from json
        return serializedJson;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        if (content.Headers.ContentType.MediaType.Contains("xml"))
        {
            var doc = SerializeToXmlDocument(type, value).ToXDocument();
            doc = ReduceXml(doc);

            var settings = new XmlWriterSettings {Encoding = new UTF8Encoding(false)};
            using (XmlWriter w = XmlWriter.Create(writeStream, settings))
            {
                doc.Save(w);
            }
        }
        else
        {
            var json = new JavaScriptSerializer().Serialize(value);
            var serializedJson = (JObject)JsonConvert.DeserializeObject(json);
            var serializedJsonString = ReduceJson(serializedJson).ToString(Newtonsoft.Json.Formatting.None);
            var writer = new StreamWriter(writeStream);
            writer.Write(serializedJsonString);
        }

        var tcs = new TaskCompletionSource<object>();
        tcs.SetResult(null);
        return tcs.Task;
    }

    public XmlDocument SerializeToXmlDocument(Type type, object value)
    {
        var serializer = new XmlSerializer(type);

        XmlDocument xmlDocument = null;

        using (var memoryStream = new MemoryStream())
        {
            serializer.Serialize(memoryStream, value);
            memoryStream.Position = 0;
            using (var xtr = XmlReader.Create(memoryStream, new XmlReaderSettings {IgnoreWhitespace = true}))
            {
                xmlDocument = new XmlDocument();
                xmlDocument.Load(xtr);
            }
        }

        return xmlDocument;
    }
}

public static class XmlExtensions
{
    public static XDocument ToXDocument(this XmlDocument xmlDocument)
    {
        using (var nodeReader = new XmlNodeReader(xmlDocument))
        {
            nodeReader.MoveToContent();
            return XDocument.Load(nodeReader);
        }
    }
}
public static class JsonExtensions
{
    public static bool IsNullOrEmpty(this JToken token)
    {
        return (token == null) ||
               (token.Type == JTokenType.Array && !token.HasValues) ||
               (token.Type == JTokenType.Object && !token.HasValues) ||
               (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
               (token.Type == JTokenType.Null);
    }
}

在格式化程序中聚合时,xml和json都有效且很好,如果不使用格式化程序发回数据,则一切正常

奇怪的东西:当我使用格式化程序并发送回Json时,它会被截断,与其长度无关。即使非常微小的物体(长度小于10k)也会在同一个物体的相同位置切断,但对于不同的物体,它们的长度不同,只有json和xml才能正常工作......

如果json没有被束缚,它也会失败:

            var writer = new StreamWriter(writeStream);
            writer.Write(ReduceJson(serializedJson));

我添加了minimal solution to show the issue

这里发生了什么?为什么使用格式化程序会截断Json但不是XML的响应内容?

1 个答案:

答案 0 :(得分:0)

好的,我发现问题是在

中使用任务 .Result;

var session = response.Result.Content.ReadAsAsync<Session>(new List<MediaTypeFormatter>() { new XmlMediaTypeFormatter { UseXmlSerializer = true }, new JsonMediaTypeFormatter() }).Result;

(和问题中未列出的其他一些机制)应该是await

.Result替换为await并将链中的所有方法标记为async - 我开始获得完整回复。