webservice简单引用

时间:2023-07-04 08:48:56

//1.创建网站
//2.新建项=>添加web服务
//运行texttweb.asmx可以通过访问http://域名/webservice/texttweb.asmx来验证了
//3.添加服务引用=>发现服务=>确定添加
//4.添加窗体调用webservive对外发布的方法,可以调用显示webservice对外开发的方法了

web服务

 using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services; /// <summary>
/// textweb 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class textweb : System.Web.Services.WebService { public textweb () { //如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod(Description="这个方法返回一个查询数据库数据结果")]
public string HelloWorld()
{
string name = "";
string conString = "data source=.;initial catalog=Texts;user id=sa;pwd=023812;";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
string sql = "select name from Student where id = 5";
SqlCommand com = new SqlCommand(sql, con);
name = com.ExecuteScalar().ToString();
}
return name;
}
[WebMethod(Description = "这个方法计算加法")]
public int Sum(int a,int b) //提供对外的调用
{
return a + b;
} }

web窗体

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="+"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="=" />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> </div>
</form>
</body>
</html>
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void Button1_Click(object sender, EventArgs e)
{
textweb web = new textweb();//实例化webservice对象
//调用webservice对象提供的方法
TextBox3.Text = web.Sum(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text)).ToString();
}
}