首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 調用 WebService 報「未將對象引用設置到對象的實例」排查指南

     編輯:程式設計綜合問答

異常信息

FaultException: 服務器無法處理請求。 ---> 未將對象引用設置到對象的實例。
at WebApplication2.WeatherWS.WeatherWSSoapClient.getWeather(String theCityCode, String theUserID) in Reference.cs:130

核心判斷:服務端拋出 NullReferenceException

客戶端代碼正常,**問題在 WebService 服務端實現中**,某處未初始化對象即調用成員。

排查步驟

  1. 查看服務端日誌/調試:在 WebService 方法 getWeather 內部打斷點,或啟用 WCF 追蹤 (system.diagnostics / system.serviceModel)。
  2. 常見服務端空引用點:
    • 數據庫連接字符串讀取失敗 (ConfigurationManager.ConnectionStrings["name"] 為 null)。
    • Session/Application 狀態對象未初始化。
    • 依賴注入容器未註冊服務,構造函數注入失敗。
    • 調用第三方 API 返回 null 直接訪問屬性。
  3. 參數傳遞驗證:客戶端傳 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 方法內部的空引用,補全防御性檢查與日誌即可解決。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved