HttpWebRequest devuelve nulo ResponseStatusCode

I'm writing a background audio agent that plays music from an online stream and also periodically checks for updates in the track name and artist. I'm attempting to use an HttpWebRequest object to get the name and artist, but whenever I call HttpWebResponse trackResponse = (HttpWebResponse)trackRequest.EndGetResponse(result); the error below is thrown.

A first chance exception of type 'System.Net.WebException' occurred in System.Windows.dll

The stack trace for the WebException is the following:

at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at AudioPlaybackAgent.AudioPlayer.TrackCallback(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)
at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()

Digging further into the trackRequest object, I find this:

ResponseStatusCode = 'trackRequest.ResponseStatusCode' threw an exception of type 'System.NullReferenceException'

and further into that, I find this:

at System.Net.HttpWebRequest.get_ResponseStatusCode()
at AudioPlaybackAgent.AudioPlayer.TrackCallback(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)
at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()

Here is the code I am using. The TrackTimerTick function is called every 20 seconds by a Timer.

public static void TrackTimerTick(object state) {
        try {
            if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing) {
                // Create a HttpWebrequest object to the desired URL.
                HttpWebRequest trackRequest = (HttpWebRequest)HttpWebRequest.Create("<track/artist url");
                // Start the asynchronous request.
                IAsyncResult result = (IAsyncResult)trackRequest.BeginGetResponse(new AsyncCallback(TrackCallback), trackRequest);
            }
        } catch (WebException e) {
            Debug.WriteLine(e.Message);
        } catch (Exception e) {
            Debug.WriteLine(e.Message);
        }
    }


    public static void TrackCallback(IAsyncResult result) {
        // State of request is asynchronous.
        HttpWebRequest trackRequest = (HttpWebRequest)result.AsyncState;
        HttpWebResponse trackResponse = (HttpWebResponse)trackRequest.EndGetResponse(result); // WebException thrown here

        using (StreamReader httpwebStreamReader = new StreamReader(trackResponse.GetResponseStream())) {
            string results = httpwebStreamReader.ReadToEnd();
            XDocument trackXml = XDocument.Load(results);

            string title = (from t in trackXml.Descendants("channel") select t.Element("title").Value).First<string>();
            string artist = (from t in trackXml.Descendants("channel") select t.Element("artist").Value).First<string>();
            if (BackgroundAudioPlayer.Instance.Track != null) {
                AudioTrack track = BackgroundAudioPlayer.Instance.Track;
                track.BeginEdit();
                track.Title = title;
                track.Artist = artist;
                track.EndEdit();
            }

        }
        trackResponse.Close();


    }

Can anyone help me fix this problem? Thank you in advance.

preguntado el 10 de marzo de 12 a las 04:03

You wouldn't happen to be accessing the response status from two threads, would you? -

I don't believe so, since TrackCallback is the only place I reference the response. -

2 Respuestas

The problem is that you call NotifyComplete() before the response is arrive. I don't understand fully what happens, but you initiate the request, you call NotifyComplete, the OS froze the agent's process, then the next time the agent wakes up the WebClient immediately throws an exception, probably by design.

So the solution is to don't call NotifyComplete until you got the response.

respondido 10 mar '12, 23:03

Could you explain this more? I tried moving the NotifyComplete()s around and managed to get the track text to come through, but then the music wouldn't pause when I clicked my in-app pause button. Could you give some more suggestions? - bfink

Well I never wrote any audio background agent, my best idea is that you still don't call the NotifyComplete at the right time. The first thing which can be a problem is that you're using a timer. Since the process is frozen between the control commands the timer's tick event won't fire between commands. If you really want to do webrequests in your audio agent (I'm not sure that is a good idea, nor you really need to.) try to initiate the request in the PlayStateChanged and call the NotifyComplete in the response callback. Without more information this is my best idea. - Loránd Biró

Thanks, that makes sense. What I want to do is have the audio background agent query the server every 20-30 seconds to get new track data, even if the main application that started the audio agent is deactivated. Would this be possible? - bfink

In my case I had to look at my project error log where normally exceptions are thrown and it was printing the message Unable to create an SSL/TLS secure channel. in System.Net.HttpWebRequest.GetResponse() and to solve this I added ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; before my request, but you can put it to be executed on your starter method or class. I think other think that you can do is to add the response in try and catch exception

try
    {
        var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            Response response = new JavaScriptSerializer().Deserialize<Response>(result);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

And here your response class

public class Response
{
    public string value_02 { get; set; }
    public string value_03 { get; set; }
    public string value_04 { get; set; }
    public string value_05 { get; set; }
    public string value_05 { get; set; }
}

Fact that for me gave the exception

Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.ObjectDisposedException' in System.dll
Exception thrown: 'System.Net.WebException' in System.dll
Exception thrown: 'System.Net.WebException' in System.dll
Exception thrown: 'System.NullReferenceException'

And I have added to solve my problem

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Solved my problem

Respondido 31 ago 21, 14:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.