You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

遇到System.NullReferenceException异常,我忽略了什么?

Fixing System.NullReferenceException in Your C# SQL CLR Function

Hey there! Let's figure out what's causing that null reference error—since you're working with a SQL CLR function that deals with web URLs, there are a handful of common mistakes that lead to this exception, even for experienced devs. Here's what to check:

  • You're not handling NULL inputs from SQL
    SQL allows NULL values, but when you pass a NULL into a SqlString (or any Sql* parameter type) in your CLR function, accessing its .Value property directly will throw a null reference. Always add a guard clause at the start of your function:

    [SqlFunction(DataAccess = DataAccessKind.None)]
    public static SqlString GetWebUrl(SqlString targetUrl)
    {
        // First, check if the input is NULL from SQL
        if (targetUrl.IsNull)
            return SqlString.Null;
        
        // Now safely use targetUrl.Value
        string url = targetUrl.Value;
        // ... rest of your code
    }
    
  • Network objects aren't being initialized
    Your code imports System.Net, so you're probably using WebClient, HttpWebRequest, or similar to fetch the URL. If you declare one of these objects without creating an instance with new, calling any method on it will trigger the exception. For example:

    // ❌ Bad: client is declared but never created
    WebClient client;
    string content = client.DownloadString(url); // NullReferenceException here
    
    // ✅ Good: Initialize the object first
    WebClient client = new WebClient();
    
  • You're not checking for null web responses
    Even if your request goes through, the server might return a null response, or the response stream could be empty. Trying to read from a null stream will throw. Add checks like this:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        // Check if the response itself is null
        if (response == null)
            return SqlString.Null;
        
        using (Stream responseStream = response.GetResponseStream())
        {
            // Check if the stream is null before reading
            if (responseStream == null)
                return SqlString.Null;
            
            // Now safely read from the stream
            using (StreamReader reader = new StreamReader(responseStream))
            {
                string result = reader.ReadToEnd();
                return new SqlString(result);
            }
        }
    }
    
  • String operations are using null values
    If you're building strings (with StringBuilder or concatenation) using values that might be null (like other SQL parameters), calling .ToString() on a null object will cause the exception. Always check for null first:

    // ❌ Bad: If sqlParam is NULL, .Value is null, and .ToString() throws
    sb.Append(sqlParam.Value.ToString());
    
    // ✅ Good: Handle null explicitly
    sb.Append(sqlParam.IsNull ? string.Empty : sqlParam.Value.ToString());
    

Since your code snippet cuts off at the SqlFunction attribute, double-check that you've set up the function correctly (including DataAccess settings if needed) and that all objects are initialized before use.

内容的提问来源于stack exchange,提问作者A. Guattery

火山引擎 最新活动