標籤:idt port src bag type tle textbox 分享 建立
在項目開發中,我們除了發布WebService提供客戶調用外,也經常需要調用一些客戶或者第三方的WebService服務,這裡就通過一個Demo來示範調用一個第三方的天氣預報服務。
1.天氣預報服務介面說明:
這裡以http://www.webxml.com.cn/WebServices/WeatherWebService.asmx這個天氣預報服務為例
2.建立空mvc項目MvcAppService
3.引入Web服務。在項目引用上右鍵,選擇“加入服務參考”,如:
4.在彈出的加入服務參考視窗單擊“進階”按鈕,如:
5.在彈出的表單中單擊“添加Web引用”按鈕,如:
6.輸入Web服務地址,修改Web引用名稱,如:
7.從 http://www.webxml.com.cn/images/weather.zip下載天氣圖片,然後解壓檔案,將檔案夾weather複製到項目Content檔案夾下(空項目沒有Content檔案夾,自己建立)
8.添加Home控制器,和兩個GetWeather方法,實現代碼。
public ActionResult GetWeather() { return View(); } [HttpPost] public ActionResult GetWeather(string city) { Weather.WeatherWebService client = new Weather.WeatherWebService(); var strlist = client.getWeatherbyCityName(city); if(strlist[8] == "") { ViewBag.Msg = "暫時不支援你查詢的城市"; } else { ViewBag.ImgUrl = @"/Content/weather/" + strlist[8]; ViewBag.General = strlist[1] + " " + strlist[6]; ViewBag.Actually = strlist[10]; } return View(); }
9.添加GetWeather視圖,代碼如下:
@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>GetWeather</title></head><body> @using (Html.BeginForm("GetWeather", "Home", FormMethod.Post)) { <div>請輸入查詢的城市:@Html.TextBox("city")<input type="submit" value="查詢" /></div> <div> 天氣概況:@ViewBag.General @if (!string.IsNullOrEmpty(ViewBag.ImgUrl as string)) { <img src="@ViewBag.ImgUrl" /> } <div>天氣實況:@ViewBag.Actually</div> <div>@ViewBag.Msg</div> </div> }</body></html>
10.運行結果如下:
WebServic調用天氣預報服務