初学WebService

来源:互联网 发布:ubuntu配置网关 编辑:程序博客网 时间:2024/06/04 23:24

1、新建一个web项目

2、在项目名称单击右键->添加->服务引用,弹出窗口后点击“高级”,再点击“添加Web服务”


3、在URL填入要引用的web服务的路径,例如(天气预报:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx),再点击傍边的“转到”按钮

4、修改好Web引用名后(例如:HttpWeatherWebService),点击”添加引用“,在项目下的文件Web References中就有刚添加的引用了


5、天气预报例子的代码

WebForm1.aspx文件的代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="GetWebService.WebForm1" %>
<!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="txtCityName" runat="server"></asp:TextBox>
            <asp:Button ID="Submit" runat="server" Text="提交" OnClick="Submit_Click" Height="21px" /><br />
            城市天气预报信息<br />
            <asp:ListBox ID="ListBox1" runat="server" Height="300px" Width="100%"></asp:ListBox>
        </div>
    </form>
</body>
</html>



WebForm1.aspx.cs文件的按钮事件代码:

protected void Submit_Click(object sender, EventArgs e)
{
            HttpWeatherWebService.WeatherWebService ws = new HttpWeatherWebService.WeatherWebService();
            string[] r = ws.getWeatherbyCityName(this.txtCityName.Text);
            this.lboxWeatherMsg.Items.Clear();
            if (r == null)
            {
                this.lboxWeatherMsg.Text = "无" + this.txtCityName.Text + "城市的天气信息";
                return;
            }
            foreach (string i in r)
            {
                this.lboxWeatherMsg.Items.Add(i);
            }
  }

运行结果


原创粉丝点击