简体   繁体   English

C#Web服务无法使用HTTP POST向其发送字节

[英]C# webservice unable to use HTTP POST to send bytes to it

I have the followind webservice defined. 我已经定义了followind Web服务。

       [WebMethod]
        public String sendBytes(byte[] a)
        {
            return "good";
        }

I am able to call it successfully using the Webservice proxy class. 我可以使用Webservice代理类成功调用它。

However I am unable to send a HTTP POST with binaries to this web method. 但是,我无法将包含二进制文件的HTTP POST发送到此Web方法。 I tried this: 我尝试了这个:

      try
           {
               HttpWebRequest request = HttpWebRequest.Create(address) as 
               HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //request.ContentLength = 0;


            var postData = "xxx";         

            var data = Encoding.UTF8.GetBytes(postData);

            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            String x = Console.ReadLine();

and I got this 我知道了

System.NullReferenceException: Object reference not set to an instance of an object. System.NullReferenceException:对象引用未设置为对象的实例。 at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection) at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request) at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest() 在System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)在System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)在System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() .Services.Protocols.WebServiceHandler.CoreProcessRequest()

The thing is I can send Strings using this method, but not binary data. 问题是我可以使用此方法发送字符串,但不能发送二进制数据。 The definition in the webservice POST Example is also wierd. webservice POST示例中的定义也很奇怪。

http://localhost:50178/WebService1.asmx?op=sendBytes http:// localhost:50178 / WebService1.asmx?op = sendBytes

I am grateful for ANY help or suggestions on this topic. 感谢您提供有关此主题的任何帮助或建议。 Thx for reading :) 阅读Thx :)

Edit: Thank you for your quick response. 编辑:感谢您的快速反应。

I think I have solved the null exception, I think the cause of it is because it cant find the param for the value that I am sending. 我想我已经解决了null异常,我想原因是因为它找不到我要发送的值的参数。 But I have another problem now: 但是我现在有另一个问题:

System.ArgumentException: Cannot convert ef to System.Byte. System.ArgumentException:无法将ef转换为System.Byte。 Parameter name: type ---> System.FormatException: Input string was not in a correct format. 参数名称:类型---> System.FormatException:输入字符串的格式不正确。 at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info) at System.String.System.IConvertible.ToByte(IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Web.Services.Protocols.ScalarFormatter.FromString(String value, Type type) --- End of inner exception stack trace --- at System.Web.Services.Protocols.ScalarFormatter.FromString(String value, Type type) at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection) at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request) at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest() 在System.Number.ParseInt32(String s,NumberStyles样式,NumberFormatInfo信息)在System.Byte.Parse(String s,NumberStyles样式)在System.Number.StringToNumber(String str,NumberStyles选项,NumberBuffer&数字,NumberFormatInfo信息,布尔parseDecimal) ,位于System.String.System.IConvertible.ToByte(IFormatProvider提供程序)处,位于System.Web.Services.Protocols.ScalarFormatter.FromString(String值,类型类型)---内部异常堆栈跟踪的结尾---在System.Web.Services.Protocols.ScalarFormatter.FromString(字符串值,类型类型)在System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection集合) System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest请求)处System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()处System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Here is the code: 这是代码:

          try
        {
            HttpWebRequest request = HttpWebRequest.Create(address) as 
           HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //request.ContentLength = 0;


            var postData = "a=";         

            var data = Encoding.UTF8.GetBytes(postData);
            byte[] bytedata = new byte[] { 0x65,0x66};
            request.ContentLength = data.Length + bytedata.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Write(bytedata, 0, bytedata.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Edit 2: I have tried Aaron's suggestion but it did not work. 编辑2:我尝试了亚伦的建议,但是没有用。

Here is the edited code: 这是编辑后的代码:

        try
        {
            HttpWebRequest request = HttpWebRequest.Create(address) as 
          HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/octet-stream";

            //request.ContentLength = 0;


            var postData = "a=";         

            var data = Encoding.UTF8.GetBytes(postData);
            byte[] bytedata = new byte[] { 0x65,0x66};
            request.ContentLength = data.Length + bytedata.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Write(bytedata, 0, bytedata.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("Sending request\n\n");
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Gave the following error: 出现以下错误:

System.InvalidOperationException: Request format is invalid: application/octet-stream. System.InvalidOperationException:请求格式无效:application / octet-stream。 at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest() 在System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()处的System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()处

Reference : How can I make a local file as body of an HttpWebRequest? 参考: 如何将本地文件作为HttpWebRequest的主体? .

The thing is i tried changing the url, because if the problem was the packet not being formed well I would get the same error, but it dint. 事情是我尝试更改url,因为如果问题是数据包格式不正确,我会遇到相同的错误,但是有点。 Could it be my webservice being wrong somewhere? 可能是我的Web服务在某处出错了吗?

Try setting the request.ContentType to application/octet-stream . 尝试将request.ContentType设置为application/octet-stream This content type is used to signal that the request body contains arbitrary binary data. 此内容类型用于表示请求主体包含任意二进制数据。

Remember that HTTP is a text based protocol that uses ASCII encoding in it's messages. 请记住,HTTP是基于文本的协议,在其消息中使用ASCII编码。 In your test data 0x65 and 0x66 are 'e' and 'f' in which is why the exception you get says "Cannot convert ef to System.Byte". 在测试数据中0x65和0x66分别是'e'和'f',这就是为什么您收到的异常提示“无法将ef转换为System.Byte”的原因。 The bytes you are trying to send are getting encoded to ASCII, therefore becoming a string, where your endpoint is expecting bytes. 您尝试发送的字节已被编码为ASCII,因此成为一个字符串,您的端点期望使用该字节。

Edit: 编辑:

You could also try using a multipart/form-data request. 您也可以尝试使用multipart / form-data请求。 Example of how to do it with C# is here: 使用C#的示例如下:

https://gist.github.com/bgrins/1789787 https://gist.github.com/bgrins/1789787

References: 参考文献:

Why Http Protocol is designed in a plain text way 为什么以纯文本方式设计Http协议

Which Mime Type to use for a binary file 二进制文件使用哪种Mime类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM