【问题标题】:WCF - How to deserialize a byte parameterWCF - 如何反序列化字节参数
【发布时间】:2017-06-06 22:21:04
【问题描述】:

我写了一个 WCF RESTful 服务,它接受字符串和字节参数。问题是,如果字节为空白,Web 服务可以正常工作,但如果字节参数中有一个值,那么我会收到以下错误消息:

'反序列化 System.Byte[] 类型的对象时出错。应来自命名空间“”的结束元素“文档”。

这是我的代码

WCF 接口

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "IDocument")]
string IndexDocument(byte[] Document, string DocumentType);

WCF 接口实现

public string IndexDocument(byte[] Document, string DocumentType)
{
}

客户端程序

 private class Documentt
        {
            public byte[] Document { get; set; }
            public string DocumentType { get; set; }
        }



static async Task RunAsync()
        {
            byte[] bytes = System.IO.File.ReadAllBytes(openFileDialog.FileName);

            var parameters = new Documentt()
            {
                Document = bytes,
                DocumentType = "AA"
            };


            using (HttpClient client = new HttpClient())
            { 
                var request = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json");

                var response = client.PostAsync(new Uri("http://localhost:59005/ServiceCall.svc/IDocument"), request);
                var result = response.Result;

            }
        }

我在这里做错了什么?我想使用字节,因为我想编写一个跨平台(供 java、c++、c# 等使用)Web 服务。

【问题讨论】:

    标签: c# json wcf


    【解决方案1】:

    那是因为您使用datacontact 作为您的解毒剂,而Json.NET 作为您的杀菌剂。请记住,它们对 DateTimeByte[] 之类的对象的行为不同。 请使用此方法序列化您的请求:

    public static string DataJsonSerializer<T>(T obj)
    {
        var json = string.Empty;
        var JsonSerializer = new DataContractJsonSerializer(typeof(T));
    
        using (var mStrm = new MemoryStream())
        {
            JsonSerializer.WriteObject(mStrm, obj);
            mStrm.Position = 0;
            using (var sr = new StreamReader(mStrm))
                json = sr.ReadToEnd();
        }
    
        return json;
    }
    

    您的请求应该是这样的:

    var request = new StringContent(DataJsonSerializer(parameters), Encoding.UTF8, "application/json");
    

    【讨论】:

    • 这工作得很好。我必须将 DataContract 和 DataMember 附加到我的 Document 类以允许此解决方案工作。谢谢你..
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2021-04-30
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多