簡體   English   中英

如何使用 c# 在 ASP.Net Web 應用程序中處理 WebException?

[英]how to handle WebException in ASP.Net Web Application using c#?

我正在通過調用第三方 api openweather 創建自己的天氣 api。 我不知道如何處理當我提供不存在的城市作為輸入時發生的 WebException,它給了我來自 openweatherapi 的狀態代碼 404,我不知道如何處理該錯誤我的應用程序總是由於未處理而崩潰例外

謝謝你的幫助:D

我正在處理的代碼

        public void WeatherDetail(string City)
        {
             
        //Assign API KEY which received from OPENWEATHERMAP.ORG  
            string appId = "*******";

            //API path with CITY parameter and other parameters.  
            string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&appid={1}", City, appId);

            using (WebClient client = new WebClient())
            {
                string json = "";
                try
                {
                    json = client.DownloadString(url);
                }
                catch (system.net.webexception)
                {
                    // how to handle WebException ?
                }
                

                //Converting to OBJECT from JSON string.  
                Root weatherInfo = (new JavaScriptSerializer()).Deserialize<Root>(json);

                //Special VIEWMODEL design to send only required fields not all fields which received from   
                ResultViewModel rslt = new ResultViewModel();
                DateTime aDate = DateTime.Now;
                string today = aDate.ToString("yyyy-MM-dd");

                rslt.Country = weatherInfo.sys.country;
                if(City == "Thane" || City == "thane")
                {
                    rslt.Name = "Thane";
                }
                else
                {
                    rslt.Name = weatherInfo.name;
                }
                rslt.Lat = weatherInfo.coord.lat;
                rslt.Lon = weatherInfo.coord.lon;
                rslt.Description = weatherInfo.weather[0].description;
                rslt.Temp = weatherInfo.main.temp;
                rslt.WeatherIcon = weatherInfo.weather[0].icon;
                rslt.Pressure = weatherInfo.main.pressure;
                rslt.Deg = weatherInfo.wind.deg;
                rslt.WindSpeed = weatherInfo.wind.speed;
                rslt.Main = weatherInfo.weather[0].main;
                rslt.WeatherId = weatherInfo.weather[0].id;
                rslt.Sunrise = weatherInfo.sys.sunrise;
                rslt.Sunset = weatherInfo.sys.sunset;
                rslt.Date = today;
                rslt.Id = weatherInfo.id;
                try
                {
                    con.Open();

                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw ex;
                }
                    cmd = new SqlCommand("insert into CityWeather (lon, lat, name, country, weatherid, main, description, temp, pressure, sunrise, sunset, windspeed, deg, weatherIcon) values (" +
                        "'" + rslt.Lon + "','" + rslt.Lat + "','" + rslt.Name + "','" + rslt.Country + "', '" + rslt.WeatherId + "','" + rslt.Main + "', '" + rslt.Description + "','" + rslt.Temp + "', '" + rslt.Pressure + "', '" + rslt.Sunrise + "','" + rslt.Sunset + "', '" + rslt.WindSpeed + "', '" + rslt.Deg + "', '" + rslt.WeatherIcon + "')"
                        , con);
                    cmd.ExecuteNonQuery();
                    con.Close();
            }
        } 

謝謝你的幫助:D

您可以檢查遠程服務是否在錯誤中返回了錯誤消息,如下所示:

catch (WebException wex)
{
    if (wex.Status == WebExceptionStatus.ProtocolError)
    {
        using (Stream responStream = wex.Response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(responStream))
            {
                String response = reader.ReadToEnd();
                //check response content here, and return an error to your client
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM