FaultException: 服務器無法處理請求。 ---> 未將對象引用設置到對象的實例。
at WebApplication2.WeatherWS.WeatherWSSoapClient.getWeather(String theCityCode, String theUserID) in Reference.cs:130
客戶端代碼正常,**問題在 WebService 服務端實現中**,某處未初始化對象即調用成員。
getWeather 內部打斷點,或啟用 WCF 追蹤 (system.diagnostics / system.serviceModel)。ConfigurationManager.ConnectionStrings["name"] 為 null)。theUserID = " " (空格),服務端若做 Trim() 後為空字符串,查詢邏輯可能返回 null 實體再訪問屬性。var client = new WeatherWS.WeatherWSSoapClient("WeatherWSSoap");
try {
// 避免重複調用
var result = client.getWeather("天津", ""); // 空字符串而非空格
if (result != null && result.Length > 0) {
// 處理結果
}
} catch (FaultException ex) {
// 記錄 ex.Detail 或 ex.Message
Log.Error(ex);
} finally {
if (client.State == CommunicationState.Faulted) client.Abort();
else client.Close();
}
[WebMethod]
public string[] getWeather(string theCityCode, string theUserID) {
// 防御性編程
if (string.IsNullOrWhiteSpace(theCityCode)) return new string[0];
var connStr = ConfigurationManager.ConnectionStrings["WeatherDB"]?.ConnectionString;
if (connStr == null) {
// 記錄錯誤,拋出有意義異常
throw new InvalidOperationException("數據庫連接字符串未配置");
}
using (var conn = new SqlConnection(connStr)) {
// 參數化查詢,避免注入
var cmd = new SqlCommand("SELECT ... WHERE City=@City", conn);
cmd.Parameters.AddWithValue("@City", theCityCode);
// ...
}
}
web.config 開啟 <compilation debug="true"> 獲取行號。svclog 記錄 WCF 完整消息:SvcTraceViewer.exe 打開分析。try-catch 記錄堆棧到文件/數據庫。**異常源頭在服務端**,客戶端僅是代理拋出。重點檢查服務端 getWeather 方法內部的空引用,補全防御性檢查與日誌即可解決。