0

In a .Net 4.7.1 targeted application I am using HttpClient to perform Http requests.

When performing a GET request for a URL that returns a Http 204 result (no content), this results in a System.NullReferenceException: 'Object reference not set to an instance of an object.'.

On top of that, the exception is not caught by the try catch, which I think has something to do with the async call, as specified in this question: Why can't I catch an exception from async code?, but I want to focus on not getting the exception in the first place.

The same request was tested in a .Net Core application using IHttpClientFactory where it works as expected.

protected async Task<HttpResponseMessage> GetResponse(string path, Dictionary<string, string> headers)

    {

        HttpResponseMessage responseMessage = null;
        var request = new HttpRequestMessage(HttpMethod.Get, path);

        if (headers != null)
        {
            foreach (var header in headers)
            {
                request.Headers.Add(header.Key, header.Value);
            }
        }

            var proxy = new WebProxy
            {
                Address = new Uri($"http://{ProxyHost}:{ProxyPort}"),
                BypassProxyOnLocal = false,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(userName: ProxyUser, password: ProxyPW)
            };

 
            // create a client handler which uses that proxy

            var httpClientHandler = new HttpClientHandler
            {
                Proxy = proxy
            };

            var httpclient = new HttpClient(httpClientHandler);

            try
            {
                responseMessage = await httpclient.SendAsync(request);
            }
            catch (Exception ex)
            {
                // handle error …
            }

        return responseMessage;

    }

The line throwing the exception is:

responseMessage = await httpclient.SendAsync(request);

Visual Studio catches the unhandled exception:

Exception

Exception details:

System.NullReferenceException

  HResult=0x80004003

  Message=Object reference not set to an instance of an object.

  Source=mscorlib

  StackTrace:

   at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback callback, Object state, Task& currentTask)

--- End of stack trace from previous location ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()

   at System.Threading.ThreadPoolWorkQueue.Dispatch()

 

  This exception was originally thrown at this call stack:

    [External Code]

An exception with StackTrace is visible in Event Viewer, but it doesn't help me a lot:

StackTrace:    at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)

   at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)

   at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state)

   at System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state)

   at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback callback, Object state, Task& currentTask)

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()

   at System.Threading.ThreadPoolWorkQueue.Dispatch()

How can I make HttpClient handle the response correctly? I have no control over the server sending the Http 204 response.

redrobot
  • 835
  • 2
  • 13
  • 30
  • It's far more likely that the code is trying to call a method on a `null`. What is the *full* exception text returned by `Exception.ToString()` ? Where is the exception raised? In this method or somewhere else? – Panagiotis Kanavos Dec 13 '22 at 09:45
  • In any case 204 won't throw any exception. If the application code tries to call the non-existent content, an NRE is possible. If the caller of this method tries to deserialize the content for example, the result will be a `null` – Panagiotis Kanavos Dec 13 '22 at 09:48
  • @PanagiotisKanavos The exception is thrown in HttpClient.SendAsync and not properly handled, therefore I am unable to view the exception details. – redrobot Dec 13 '22 at 09:55
  • How do you know there's an exception in that case? Somehow, somewhere, you get a notification, a popup or a log message. Try debugging your code to find where the exception is thrown. Visual Studio's exception popup has a link button that copies the entire exception text to the clipboard. Post the *full* text, including the location and stack trace – Panagiotis Kanavos Dec 13 '22 at 09:56
  • In recent VS versions the IDE will also tell you *which* variable or property was null – Panagiotis Kanavos Dec 13 '22 at 09:58
  • Added the screenshot from Visual Studio – redrobot Dec 13 '22 at 10:02
  • I am using VS 2022 – redrobot Dec 13 '22 at 10:03
  • Post the details, not the screenshot. Click on `Copy Details` and post the text in the question – Panagiotis Kanavos Dec 13 '22 at 10:05
  • I added the details and an exception from event viewer. Both don't help me out really. – redrobot Dec 13 '22 at 10:11
  • On the contrary, `System.Web.LegacyAspNetSynchronizationContext.CallCallback` may point to a misconfigured ASP.NET 4.0 application. There's a [similar question](https://stackoverflow.com/questions/38119095/async-await-throws-nullreferenceexception-how-can-we-diagnose-where-we-messed-it) containing this particular call. The solution is to set `targetFramework` in `web.config` to 4.5 or later – Panagiotis Kanavos Dec 13 '22 at 10:54
  • Aha! Targetframework was indeed not set in httpruntime. Which revealed the async method not being called correctly in the asp.net page, which resolved the whole thing apparently. Do you want to post an answer? – redrobot Dec 13 '22 at 12:58

0 Answers0