XSLT存档  

不及格的程序员-八神

 查看分类:  ASP.NET XML/XSLT JavaScripT   我的MSN空间Blog
Asked 10 years, 4 months ago
Viewed 27k times

I am trying to call a [webmethod] from C#. I can call simple webmethod that take in 'string' parameters. But I have a webmethod that takes in a 'byte[]' parameter. I am running into '500 internal server error' when I try to call it. Here is some example of what I am doing.

Lets say my method is like this

[WebMethod]
public string TestMethod(string a)
{
    return a;
}

I call it like this using HttpRequest in C#

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Credentials = CredentialCache.DefaultCredentials;
            req.Method = "POST";
            // Set the content type of the data being posted.
            req.ContentType = "application/x-www-form-urlencoded";

            string inputData = "sample webservice";
            string postData = "a=" + inputData;
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] byte1 = encoding.GetBytes(postData);

            using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
            {
                StreamReader sr = new StreamReader(res.GetResponseStream());
                string txtOutput = sr.ReadToEnd();
                Console.WriteLine(sr.ReadToEnd());
            }

This works perfectly fine. Now I have another webmethod that is defined like this

[WebMethod]
public string UploadFile(byte[] data)

I tried calling it like this

            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "data=abc";
            byte[] sendBytes = encoding.GetBytes(postData);
            req.ContentLength = sendBytes.Length;
            Stream newStream = req.GetRequestStream();
            newStream.Write(sendBytes, 0, sendBytes.Length);

But that gives me a 500 internal error :(

 

4 Answers

5

it is possible, I have done it myself

First the Header settings, this can be obtained if your webservice can be executed via web and sending the parameters. I use the Developer tools from Chrome. The easy way is to review the description of the webservice (i.e. http ://myweb.com/WS/MyWS.asmx?op=Validation)

WebRequest request = WebRequest.Create(http://myweb.com/WS/MyWS.asmx?op=Validation);
request.Method = "POST";
((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";
request.ContentType = "text/xml; charset=utf-8";
((HttpWebRequest)request).Referer = "http://myweb.com/WS/MyWS.asmx?op=Validation";
((HttpWebRequest)request).Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
((HttpWebRequest)request).Host= "myweb.com";
 request.Headers.Add("SOAPAction","http://myweb.com/WS/Validation");

Then the request part

string message = "a=2";
string envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
        "<soap:Body><Validation xmlns=\"http://myweb.com/WS\"><data>@Data</data></Validation></soap:Body></soap:Envelope>";
string SOAPmessage = envelope.Replace("@Data",   System.Web.HttpUtility.HtmlEncode(message));
// The message must be converted to bytes, so it can be sent by the request
byte[] data = Encoding.UTF8.GetBytes(SOAPmessage);
request.ContentLength = data.Length;
request.Timeout = 20000;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Stream inputStream = response.GetResponseStream(); 

Now you can get the incoming stream from the response

Remember to adapt the SOAP envelop and the parameters to be sent according to the description given by the page details from the webservice (i.e. http ://myweb.com/WS/MyWS.asmx?op=Validation).

 
3

You are using the HTTP POST/HTTP GET capability of the ASP.NET Web Service plumbing instead of sending an actual web-service call. This is a mechanism that allows you to test simple web services but it isn't really designed for use in a production application. In fact if you navigate to the web-service URL you'll find that it can't even display a test input form for that type of parameter. It might be possible to figure out a way to trick it into working, but to be honest, you should just use it the way it is intended and generate a web service proxy.

Within Visual Studio right mouse click on the project containing the client code and select Add Service or Web Reference. Then type in the URL to the web-service and it will generate a proxy. If you are using WCF it'll look something like this:

// ServiceNameClient is just a sample name, the actual name of your client will vary.
string data = "abc";
byte[] dataAsBytes = Encoding.UTF8.GetBytes(data);
ServiceNameClient client = new ServiceNameClient();
client.UploadFile(dataAsBytes);

Hope this helps.

 
  •  
    lets say I was using C++ and HttpOpenRequest.. how would I do it then? – shergill Apr 2 '09 at 16:44
  •  
    Not sure off the top of my head :) – Mitch Denny Apr 4 '09 at 0:19
  • 2
    If the above code works you could use Fiddler to see how the http request is constructed and then use that information to get your custom code to work. – Damien McGivern Aug 3 '09 at 13:29
  •  
    fiddler2.com/fiddler2 – Damien McGivern Aug 3 '09 at 13:29
0

You will probably need to base64 encode the binary data.

But the 500 error is a clue to look in the Windows event log and see what happened on the server side.

 
0

string postData = "data=abc";

guess you should pass byte array as array, not a base64 string. for example:

string postData = "data=97&data=98&data=99"; //byte array for abc is [97,98,99]

please refer to https://www.codeproject.com/Tips/457410/Xml-WebService-Array-Parameters

shareimprove this answer


Xml-WebService Array Parameters

Praveen Kumar Chauhan (PRK)
 
Rate this:
5.00 (1 vote)
 
12 Sep 2012CPOL
Sending Data Through XML to web Services

Introduction

This article explains how you can forward data through XML on WSDL base web services. The best part of this approach is you can forward a list of array and bytes array which enables you to forward files and images to the server using the HTTPRequest class.

Background

As we all know Visual Studio provides a pretty good option to their users to consume web services (i.e., 'Add Service Reference') which will create a client as an object in a project and the programmer can call the respective method using that client object easily, but it mostly helps other platform developers (e.g., Android, Java) if we know how others can consume our created web services.

Using the Code

So here we start. As we are working with web services, we need to write a webservice in a project.

[WebMethod]
public void GetResult(int[] value)
{
      var Sample = value;
}

Now calling the above webservice method using the HttpWebRequest class:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
    "http://localhost:3190/WebSite1/WebService.asmx">http://localhost:3190/WebSite1/WebService.asmx");
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";

string xml = @"<?xml version='1.0' encoding='utf-8'?>
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
      xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
      xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
  <soap:Body>
    <GetResult xmlns='http://tempuri.org/'>
      <value>
        <int>5</int>
        <int>4</int>
      </value>
    </GetResult>
  </soap:Body>
</soap:Envelope>";

byte[] xmlData = System.Text.Encoding.ASCII.GetBytes(xml);
Stream str = request.GetRequestStream();
str.Write(xmlData, 0, xmlData.Length);
HttpWebResponse responce = (HttpWebResponse)request.GetResponse();

Points of Interest

The point you have to keep in your mind is that the byte[] you are sending should be endoded in 64 base binary format.

The way to write XML and request content types will be provided in your webservice details.

 

License

posted on 2019-08-26 13:13  不及格的程序员-八神  阅读(7)  评论(0编辑  收藏  举报