【问题标题】:WCF post a byte[] to service?WCF 将 byte[] 发布到服务?
【发布时间】:2017-04-08 17:09:47
【问题描述】:

我正在尝试将 byte[] 或 FromBase64String 字符串发布到我的网络服务。我不断收到 404 错误。我已将 ["Content-type"] 更改为 "text/plain",但仍然出现错误。但是,当我注释掉 byteArray 时,一切都很好。有人有建议吗?

客户:

      Object _object = new Object
        {
            Param1String = "data",
            Param2String= "data",           
            Param3String = "data",
            ByteArray = ReadAllBytes(@"C:\Folder\test.pdf")
        };

        try
        {
            WebClient Proxy = new WebClient();                
            Proxy.Headers["Content-type"] = "application/json";                
            MemoryStream stream = new MemoryStream();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Object));
            serializer.WriteObject(stream, _object);
            byte[] data = Proxy.UploadData("http://localhost:4589/TestService.svc/FileUpload", "POST", stream.ToArray());

            stream = new MemoryStream(data);
            serializer = new DataContractJsonSerializer(typeof(Object));
            var result = serializer.ReadObject(stream) as Object;
            Console.WriteLine(result.Param1String);
            Console.ReadKey(true);
        }
        catch (Exception ex)
        {

        }

服务:

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/FileUpload")]
    void FileUpload(Patron patron);

    public void FileUpload(Object patron)
    {

            byte[] newBytes = null;
            BinaryWriter Writer = null;
            string Name = @"C:\\Temp\\" + object.Param1String + "";
            //byte[] bData = Helper.CopyToArray(object.ByteArray);

            try
            {
                newBytes = Convert.FromBase64String(patron.ByteArray);
                Writer = new BinaryWriter(File.OpenWrite(Name));                    
                Writer.Write(newBytes);
                Writer.Flush();
                Writer.Close();
            }
            catch
            {                    
                //return false;
            }
        }

【问题讨论】:

    标签: c# web-services wcf http-post


    【解决方案1】:

    在序列化对象之前,您需要对文件内容进行 base64 编码。并将其转换回另一边的 byte[]

    Object _object = new Object
        {
            Param1String = "data",
            Param2String= "data",           
            Param3String = "data",
            Base64ByteArray =  Convert.ToBase64String(ReadAllBytes(@"C:\Folder\test.pdf"))
        };
    

    【讨论】:

      猜你喜欢
      • 2014-11-30
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多