新增了Description屬性,說明此方法的用途
根據伺服器當前時間動態生成不同的問候語
使用字串插補($"{}")來創建包含時間的訊息
[WebMethod(Description = "返回一個簡單的問候訊息")]
public string HelloWorld()
{
// 獲取當前伺服器的時間
DateTime currentTime = DateTime.Now;
// 根據時間生成適當的問候語
string greeting;
if (currentTime.Hour < 12)
{
greeting = "早安";
}
else if (currentTime.Hour < 18)
{
greeting = "午安";
}
else
{
greeting = "晚安";
}
// 返回包含時間的問候訊息
return $"{greeting}!現在伺服器時間是:{currentTime.ToString("yyyy-MM-dd HH:mm:ss")}";
}
接受一個名為name的字串參數
檢查參數是否為空
生成一個包含使用者名字的定制問候訊息
[WebMethod(Description = "返回根據名字定制的問候訊息")]
public string SayHello(string name)
{
// 檢查是否提供了名字參數
if (string.IsNullOrEmpty(name))
{
return "請提供您的名字!";
}
// 獲取當前伺服器的時間
DateTime currentTime = DateTime.Now;
// 根據時間生成適當的問候語
string greeting;
if (currentTime.Hour < 12)
{
greeting = "早安";
}
else if (currentTime.Hour < 18)
{
greeting = "午安";
}
else
{
greeting = "晚安";
}
// 返回包含名字和時間的問候訊息
return $"{name},{greeting}!現在伺服器時間是:{currentTime.ToString("yyyy-MM-dd HH:mm:ss")}";
}
右鍵點擊專案名稱
選擇「新增」→「類別」
命名為WeatherInfo.cs
添加右邊代碼
using System;
// 定義一個可序列化的類來表示天氣資訊
[Serializable]
public class WeatherInfo
{
// 城市名稱
public string City { get; set; }
// 當前溫度(攝氏度)
public double Temperature { get; set; }
// 天氣情況(晴、陰、雨等)
public string Condition { get; set; }
// 濕度百分比
public int Humidity { get; set; }
// 更新時間
public DateTime UpdateTime { get; set; }
}
HelloWorldService.asmx.cs檔案
添加右邊方法
[WebMethod(Description = "獲取指定城市的模擬天氣資訊")]
public WeatherInfo GetWeatherInfo(string city)
{
// 在實際應用中,這裡應該查詢資料庫或調用外部天氣API
// 這裡我們僅返回模擬數據作為示範
// 創建一個天氣資訊實例
WeatherInfo weatherInfo = new WeatherInfo();
// 設置城市名稱
weatherInfo.City = string.IsNullOrEmpty(city) ? "默認城市" : city;
// 生成一個模擬溫度(15-30度之間的隨機數)
Random random = new Random();
weatherInfo.Temperature = Math.Round(15 + random.NextDouble() * 15, 1); // 保留一位小數
// 根據溫度設置天氣情況
if (weatherInfo.Temperature < 20)
{
weatherInfo.Condition = "陰涼";
weatherInfo.Humidity = random.Next(40, 60);
}
else if (weatherInfo.Temperature < 25)
{
weatherInfo.Condition = "舒適";
weatherInfo.Humidity = random.Next(30, 50);
}
else
{
weatherInfo.Condition = "炎熱";
weatherInfo.Humidity = random.Next(20, 40);
}
// 設置更新時間為當前時間
weatherInfo.UpdateTime = DateTime.Now;
return weatherInfo;
}
使用PowerShell以系統管理員身分執行以下命令,信任開發憑證
dotnet dev-certs https --trust