ASP.NET Web Service interface creation and calling method tutorial-code:9527 - 博客

Create a Web Service

1. Create a new ASP.NET website (I use Visual Studio 2013)

a. Open Visual Studio 2013, click File —> New —> Website
Insert picture description here
b. Select ASP.NET Web Application
Insert picture description here
2. Find the newly created website under Solution Explorer, right-click, and select —> Add —> New Item
Insert picture description here
3. Select "Web Service"
Insert picture description here
4. Open WebService.cs, as shown below, you can write logic code in the modified file. [WebMethod] declares a web service method that can be called by the server (equivalent to exposing to the client ), if you don’t want to be exposed by the client, you don’t need to write [WebMethod].
Insert picture description here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
 
/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://student.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    
    
 
    public WebService () {
    
    
        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }
    
    private SqlCommand cmd=null;
    private SqlConnection conn=null;
    private String sql=null;
    ///创建数据库连接方法封装
    public void openDatabase() {
    
    
        conn = new SqlConnection();
        conn.ConnectionString ==System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        if (conn.State == ConnectionState.Closed)
        {
    
    
            conn.Open();
            //Response.Write("<script>alert('Connected!');</script>");
        }
    }
  
  ///根据员工工号查询职员的信息
  ///web service 的返回值必须是可序列化的,而qlDataReader类型不能被序列化会出错,这里用DataSet类型
     [WebMethod]
    public DataSet Staff(String gonghao)
    {
    
    
            openDatabase();
            String sql = "select * from S where 员工='" + gonghao+ "'";
            SqlDataAdapter sqlad = new SqlDataAdapter(sql, conn);//创建SqlDataAdapter对象并执行sql查询
            DataSet ds = new DataSet();
            sqlad.Fill(ds);
            if (conn.State != ConnectionState.Closed)
            {
    
    
                conn.Close();
            }
            return ds;
    }
    
     //更新修改职员信息
    //数据库中身高、体重为float类型,若height、weight为“”空会出错,将其赋值null
     [WebMethod]
     public Boolean UpdateStaff(String gonghao, String height, String weight,String used_name,String email)
     {
    
    
         String strError = "";
         String sql = "update S set ";
         
         if (height.Trim() == "") {
    
     
             height = null;
         }
         else {
    
     
             float.Parse(height);
             sql=sql+"身高="+height+",";
         }
         if (weight.Trim() == "")
         {
    
    
             weight = null;
         }
         else
         {
    
    
             float.Parse(weight);
             sql=sql+ "体重=" + weight + ",";
         }
         if (used_name.Trim() != "") sql = sql + "曾用名='" + used_name + "',";//曾用名为数据库字段名
         if (email.Trim() != "") sql = sql + "电子邮件='" + email+ "',";
         sql = sql.TrimEnd(',') + " where 员工工号='" + gonghao+ "'"; 
         try
         {
    
    
             openDatabase();
             cmd = new SqlCommand(sql,conn);
             int count = cmd.ExecuteNonQuery();
             return !(count<1);
         }
         catch(Exception e){
    
    
             strError = "更新数据库失败:" +e.Message;
             return false;
         }
         finally
         {
    
    
             if (conn.State != ConnectionState.Closed)
             {
    
    
                 conn.Close();
             }
         }
     }
    
}

5. Start running the project, you can view the test call page in the browser, you can see that the Staff and UpdateStaff methods can be called
Insert picture description here
. 6. Click Staff to enter, enter gonghao (work number) to make test calls
Insert picture description here

Two Web Service client calls

1. Use IIS to publish the Web Service we just generated

a. Open IIS, find "Website", right-click "Add Website", and select the physical path of the previously built project. After adding, you can enter the example (my) in the browser: http://142.2.70.99/mfgpgm/Service.asmx to view
Insert picture description here
2. Create a new ASP.NET website, find the new project name in the solution explorer, right click, Select "Add"—>"Service Reference"
Insert picture description here
3. Click Advanced—>Add Web Reference—>Enter the published address and click the arrow—>Click Add Reference (as shown below)

Insert picture description here
Insert picture description here
Insert picture description here
4. As shown in the figure below, a WebReference will be generated, which can be called in the code (as shown in the figure below).
Insert picture description here
5. At this point, the creation of the entire WebService is successfully completed.

If you like bloggers, you can click to follow and add one-click triple link, and the source code of various systems has been uploaded to the homepage resources, welcome to download

Guess you like

Origin blog.csdn.net/Jacob946/article/details/114303431