VS2010Webservice项目开发实例

因为和VS2005存在很大差异,本文主要讲述一个简单的VS2010开发和测试Webservice项目.

主要流程为:

1.打开VS2010

2.新建立C#空白解决方案

3.添加新项目,选择左侧"已安装的模板"--"Visual C#"--"WCF",选择中间的"WCF 服务应用程序"--输入项目名称"WcfService1".新建完成后,打开项目中的Service1.svc文件,查看代码,在末尾添加两个函数.HelloWorld()和Add( int  a,  int  b).代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service1”。
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
        public  String HelloWorld()

       {

          return   " Hello, world! " ;

        }
        public   int  Add( int  a,  int  b)

        {

          return  a  +  b;

        }


    }
}

4.添加新项目,选择左侧"已安装的模板"--"Visual C#"--"Windows 窗体应用程序",选择中间的"Windows 窗体应用程序"--输入项目名称"TestService".新建完成后,双击项目中的Form1.cs文件,在界面中拖入一个menuStrip1菜单控件,加入"menuStrip1",依次输入"WebService方法调用","HelloWorld","Add",分别双击"HelloWorld"和"Add"菜单文字.产生点击事件.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestService
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void helloWorldToolStripMenuItem_Click(object sender, EventArgs e)
        {

            WcfService1.Service1 client = new WcfService1.Service1();

            // 使用 "client" 变量在服务上调用操作。

            // 始终关闭客户端。
            this.richTextBox1.Text = client.HelloWorld();

        }

        private void addToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WcfService1.Service1 client = new WcfService1.Service1();

            // 使用 "client" 变量在服务上调用操作。

            // 始终关闭客户端。
            int result = client.Add(1, 2);
            this.richTextBox1.Text = Convert.ToString(result);
        }
    }
}
5.选中TestService项目,点击鼠标右键,选择"设置为启动项目",按F5运行,点击"HelloWorld"和"Add"菜单即可看见运行效果.

原文地址:https://www.cnblogs.com/xqf222/p/3306785.html