開發一個天氣+新聞聚合小工具,需求:
技術棧:.NET Framework / .NET Core,Newtonsoft.Json、System.Xml.Serialization、HttpClient。
https://api.map.baidu.com/telematics/v3/weather?location={城市}&output=json&ak={你的AK}
需在百度開放平台申請 AK(Access Key)。
// 根對象
public class BaiduWeatherResponse {
public int error { get; set; }
public string status { get; set; }
public string date { get; set; }
public List results { get; set; }
}
public class WeatherResult {
public string currentCity { get; set; }
public string pm25 { get; set; }
public List index { get; set; }
public List weather_data { get; set; }
}
public class LifeIndex {
public string title { get; set; } // 穿衣、洗車、旅遊...
public string zs { get; set; } // 指數等級
public string tipt { get; set; } // 指數類型
public string des { get; set; } // 詳細建議
}
public class WeatherData {
public string date { get; set; } // "周一 10月27日 (實時:19℃)"
public string dayPictureUrl { get; set; }
public string nightPictureUrl { get; set; }
public string weather { get; set; } // "多雲"
public string wind { get; set; } // "西南風3-4級"
public string temperature { get; set; } // "21 ~ 16℃"
}
public static async Task GetWeatherAsync(string city, string ak) {
using var client = new HttpClient();
string url = $"https://api.map.baidu.com/telematics/v3/weather?location={Uri.EscapeDataString(city)}&output=json&ak={ak}";
string json = await client.GetStringAsync(url);
return JsonConvert.DeserializeObject(json);
}
https://ip.taobao.com/service/getIpInfo.php?ip={IP地址}
返回:國家、地區、城市、ISP 等。
// 在 Controller 或 Middleware 中
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
// 若在反向代理後需讀 Header
// var ip = Request.Headers["X-Forwarded-For"].FirstOrDefault()?.Split(',')[0].Trim();
public class IpLocation {
public int code { get; set; }
public IpData data { get; set; }
}
public class IpData {
public string city { get; set; }
public string region { get; set; }
public string isp { get; set; }
}
public static async Task GetCityByIpAsync(string ip) {
using var client = new HttpClient();
string json = await client.GetStringAsync($"https://ip.taobao.com/service/getIpInfo.php?ip={ip}");
var result = JsonConvert.DeserializeObject(json);
return result?.data?.city ?? "未知城市";
}
https://news.baidu.com/n?cmd=7&loc=0&name=%B1%B1%BE%A9&tn=rss
// name 為 URL 編碼的分類名,如 "新聞"、'體育' 等
[XmlRoot("rss")]
public class RssFeed {
[XmlElement("channel")]
public Channel Channel { get; set; }
}
public class Channel {
public string title { get; set; }
public string link { get; set; }
public string description { get; set; }
public string language { get; set; }
public string lastBuildDate { get; set; }
[XmlElement("item")]
public List Items { get; set; }
}
public class RssItem {
public string title { get; set; }
public string link { get; set; }
public string pubDate { get; set; }
public string guid { get; set; }
public string source { get; set; }
public string author { get; set; }
[XmlElement("description")]
public string Description { get; set; } // 包含 HTML 摘要
}
public static RssFeed ParseRss(string xmlContent) {
var serializer = new XmlSerializer(typeof(RssFeed));
using var reader = new StringReader(xmlContent);
return (RssFeed)serializer.Deserialize(reader);
}
// 使用
string rssXml = await new HttpClient().GetStringAsync(rssUrl);
var feed = ParseRss(rssXml);
foreach (var item in feed.Channel.Items) {
Console.WriteLine($"{item.pubDate} - {item.title} - {item.link}");
}
public class WeatherController : Controller {
private readonly string _baiduAk = "your_ak_here";
public async Task Index() {
// 1. 獲取 IP
string ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "127.0.0.1";
// 本地測試可用固定公網 IP
// 2. 解析城市
string city = await IpHelper.GetCityByIpAsync(ip);
ViewBag.City = city;
// 3. 獲取天氣
var weather = await WeatherHelper.GetWeatherAsync(city, _baiduAk);
ViewBag.Weather = weather?.results?.FirstOrDefault();
// 4. 獲取新聞
var news = await NewsHelper.GetNewsAsync("新聞");
ViewBag.News = news?.Channel?.Items?.Take(10);
return View();
}
}
Uri.EscapeDataString;RSS 可能為 GB2312,需指定 Encoding.GetEncoding("gb2312") 讀取流。https://。xmlns 需在 XmlSerializer 構造時指定 XmlRootAttribute 或使用 XDocument + LINQ to XML 更靈活。本文展示了 C# 從 IP 定位 → 城市天氣 → 新聞聚合的完整鏈路:HttpClient 異步請求、Newtonsoft.Json 處理天氣/IP JSON、XmlSerializer 解析 RSS XML、實體類映射最佳實踐。代碼結構清晰,易於擴展為微服務或定時任務推送場景。