一个简单WebService

 最近一直在弄接口方面的东西,今天想着学学c#怎么创建webservice程序。因为自己从来没有过c#的经验所以后续还是得多学习

 1、新建项目

2、选择 空模板

 

3、右键 添加 新建项 选择【web服务】

 4、写好方法,右键运行

 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebServiceDemo
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod(Description ="求和的方法")]
        public int Add(int x, int y)
        {
            return x + y;
        }
        [WebMethod(Description = "求积的方法")]
        public int Sum(int x, int y)
        {
            return x * y;
        }
    }
}
View Code

显示结果:

 

  5、完成后右键 发布:

 

 

6、发布完成,如果你有自己服务器就可以部署自己服务器上去,这里我已经部署好自己服务器上并正常访问(部署记得注意授权文件)

 访问结果:

 

 7、完成后,现在 来调用webservice,首先添加 winform程序。添加最基本的控件。一个button用来触发事件,一个label用来显示事件结果。

 

 8、右键【引用】选择【添加服务引用】

 9、填写 访问 服务连接

 

 

 

 

 编写代码

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            //实例化接口对象
           ServiceReference1.WebService1SoapClient client = new ServiceReference1.WebService1SoapClient();
            //调用方法
            int province = client.Add(15,15);
           this.label1.Text = ""+province+"";
           
        }
    }
}
View Code

10、显示结果:

 

posted @ 2021-02-26 11:45  羊羊君  阅读(103)  评论(0编辑  收藏  举报