Web Service Demo

有了Web Service的一些基础,具体如何实现,通过亲自写一个Demo来理解一下。

1.创建一个空的Web项目

 2.在Web项目下ADD一个Web Service

3.在Web service中写个简答的方法

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

namespace Demo
{
    /// <summary>
    /// WebService Demo
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]//WebService别名
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Myservice : System.Web.Services.WebService
    {
        [WebMethod]//特性
        public int add(int a, int b)
        {
            return a * b;
        }
    }
}
Myservice.asmx

4.项目完成,开始发布。

 4.1 Publish method选择File System 

     Target Location 选择要存放的位置

     勾选Delete选项

 4.2 发布成功 提示如下

5 开始部署

控制面板->程序->启用或关闭Windows功能

 

 6.输入http://localhost/iisstart.htm验证是否成功安装IIS

7打开IIS管理器

 界面如下:

 在Default Web Site下添加应用程序,别名随便取,应用程序池匹配.NET框架版本,物理路径选择发布路径

 Error 1: 根据提示打开操作中的启用。

也有出现权限错误的 需要把权限打开可以百度参考。

成功后界面如下:

点击Myservice.asmx,跳转。

 以上就是Myservice中的方法。

8 在项目中添加webservice. 地址写对应的Web service 的位置直到asmx。

添加完引用后可以使用了。

可能出现的错误: 

 这种情况说明 binding了两个,在Config文件中删除一个 ,留下一个。

 为了可以远程访问,Web config中需要写

   <webServices>
      <protocols>
        <add name="HttpPost"/>
        <add name="HttpGet"/>
      </protocols>
        </webServices>
远程访问

 最后看下调用:

private void button1_Click(object sender, EventArgs e)
        {   int b=5;
            int c=7;
            ServiceReference1.MyserviceSoapClient a = new ServiceReference1.MyserviceSoapClient();
            string g=a.add(b, c).ToString();
            MessageBox.Show(g);
        }
在按钮事件中调用Web Service

以上就是完整的一个小Demo

原文地址:https://www.cnblogs.com/cdjbolg/p/11792924.html