这个是一个简单的web服务实例,客户端通过添加web引用,使用编译好的web服务来查询特定城市的天气信息,由于只是作为模拟,所以没有使用到具体的数据库。下面给大家先看看服务器端的代码:
- using System;
- using System.Web;
- using System.Web.Services;
- using System.Web.Services.Protocols;
- [WebService(Namespace = "http://longqi293.com/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- public class Service : System.Web.Services.WebService
- {
- public Service () {
-
-
- }
- public enum TemperatureType
- {
- Fahrenheit,
- Celsius
- }
- public enum TemperatureCondition
- {
- Rainy,
- Sunny,
- Cloudy,
- Thunderstorm
- }
- public class GetWeatherRequest
- {
- public string city;
- public TemperatureType TemperatureType;
- }
- public class GetWeatherResponse
- {
- public TemperatureCondition Condition;
- public int Temperature;
- }
- [WebMethod]
- public GetWeatherResponse GetWeather(GetWeatherRequest req)
- {
- GetWeatherResponse resp = new GetWeatherResponse();
- Random r = new Random();
- int celsius = r.Next(-20, 50);
- if (req.TemperatureType == TemperatureType.Celsius)
- {
- resp.Temperature = celsius;
- }
- else
- {
- resp.Temperature = (212 - 32) / 100 * celsius + 32;
- }
- if (req.city == "Kunming")
- {
- resp.Condition = TemperatureCondition.Sunny;
- }
- else
- {
- resp.Condition = (TemperatureCondition)r.Next(0, 3);
- }
- return resp;
- }
-
-
- }
|
下面你需要先运行这个服务但是注意进行如下图的选择:

之后看到下图,记住那http地址:

至此,服务器端开发完毕。下面进入客户端开发,我们使用的是win form形式的,界面如下图:

在“项目”种选择“添加web引用”,输入刚才记下的http地址,如下图:

将引用名改为WeatherService,在程序头添加using webserviceClient.WeatherService;
之后再添加按钮“获取天气”的click事件代码如下:
- private void button1_Click(object sender, EventArgs e)
- {
- GetWeatherRequest req = new GetWeatherRequest();
- if (radioButton1.Checked == true)
- {
- req.TemperatureType = TemperatureType.Celsius;
- }
- else
- {
- req.TemperatureType = TemperatureType.Fahrenheit;
- }
- req.city = textBox3.Text;
- Service ws = new Service();
- GetWeatherResponse resp = ws.GetWeather(req);
- textBox1.Text = resp.Condition.ToString();
- textBox2.Text = resp.Temperature.ToString();
-
- }
|
最后运行如下图:
