Csharp/CSharp Tutorial/Network/WebService — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 12:20, 26 мая 2010

Simplest web method

<%@ WebService Language="C#" Class="HelloWebService" %>
using System;
using System.Web.Services;
public class HelloWebService
{
  [WebMethod]
  public string HelloWorld()
  {
    return "Hello World";
  }
}

Simple WebService

<%@ WebService Language="c#" Class="MathService"%>
using System;
using System.Web.Services;
[WebService(Namespace="http://localhost/test")]
public class MathService : WebService
{
   [WebMethod]
   public int Add(int a, int b)
   {
     return a + b;
   }
   [WebMethod]
   public int Subtract(int a, int b)
   {
      return a - b;   
   }
   [WebMethod]
   public int Multiply(int a, int b)
   {
      return a * b;
   }
   [WebMethod]
   public int Divide(int a, int b)
   {
      int answer;
      if (b != 0)
      {
         answer = a / b;
         return answer;
      } else
         return 0;
   }
}
///////////////
using System;
class ServiceTest
{
   public static void Main(string[] argv)
   {
      MathService ms = new MathService();
      int x = Convert.ToInt16(argv[0]);
      int y = Convert.ToInt16(argv[1]);
      int sum = ms.Add(x, y);
      int sub = ms.Subtract(x, y);
      int mult = ms.Multiply(x, y);
      int div = ms.Divide(x, y);
      Console.WriteLine("The answers are:");
      Console.WriteLine("  {0} + {1} = {2}", x, y, sum);
      Console.WriteLine("  {0} - {1} = {2}", x, y, sub);
      Console.WriteLine("  {0} * {1} = {2}", x, y, mult);
      Console.WriteLine("  {0} / {1} = {2}", x, y, div);
   }
}

Web service client

using System;
using System.IO;
using System.Net;
using System.Xml.XPath;
public class MainClass{
  public static void Main(string [] args) {
    string content = "productCode=1111";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:80/Query.asmx/GetNumberInStock");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = content.Length;
    StreamWriter streamWriter = new StreamWriter(request.GetRequestStream( ));
    streamWriter.Write(content);
    streamWriter.Flush( );
    WebResponse response = request.GetResponse( );
    Stream stream = response.GetResponseStream( );
    XPathDocument document = new XPathDocument(stream);
    XPathNavigator nav = document.CreateNavigator( );
    XPathNodeIterator nodes = nav.Select("//int");
    Console.WriteLine(nodes.Current);
  }
}