Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

HttpWebRequest is unable to get a response from MVC3 action

I am running a following code on Windows Phone:

        string baseAddress = tcAddress + "/Api/Audio/RegisterAudioThoughtUpload/";
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";

        int total = 1633;

        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string json = "{ \"AnonymousUserId\":\"" + Guid.NewGuid().ToString() + "\", \"TotalSize\":\"" + total.ToString() + "\" }";

            streamWriter.Write(json);
            streamWriter.Close();
        }

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            int statusCode = (int)response.StatusCode; \\At this point response is null
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string results = reader.ReadToEnd();
            response.Close();
        }

Basically I am trying to send a json-packed guid and an int to an mvc3 action.

On the server side, the processing action is:

    [HttpPost]
    public JsonResult RegisterAudioThoughtUpload(string AnonymousUserId, int TotalSize)
    {
        var aUId = Guid.Parse(AnonymousUserId);

        return new JsonResult {Data = Guid.NewGuid()};
    }

A fiddler2, that is logging the communication shows, that the server is providing a client an expected response:

fiddler2

But on the client, a call to GetResponse() just times out, never actually getting a response back.

Since it is Windows Phone, a GetResponse() is implemented the following way:

    private const int DefaultRequestTimeout = 15000;

    public static HttpWebResponse GetResponse(this HttpWebRequest request)
    {
        var dataReady = new AutoResetEvent(false);
        HttpWebResponse response = null;
        var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
        {
            response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            dataReady.Set();
        });

        request.BeginGetResponse(callback, request);

        if (dataReady.WaitOne(DefaultRequestTimeout))
        {
            return response;
        }

        return null;
    }

Why I am not getting an instance of HttpWebResponse, even though I see through proxy, that it is being sent?

Upvotes: 1

Views: 932

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

Since this is a WP application I would recommend you avoid blocking the main UI thread. I'd also recommend you using a JSON serializer instead of manually build JSON strings. So let's start by defining our models:

[DataContract]
public class Request
{
    [DataMember]
    public string AnonymousUserId { get; set; }

    [DataMember]
    public int TotalSize { get; set; }
}

and then:

var dataToSend = new Request
{
    AnonymousUserId = Guid.NewGuid().ToString(),
    TotalSize = 123
};
var serializer = new DataContractJsonSerializer(typeof(Request));
var request = string.Empty;
using (var stream = new MemoryStream())
{
    serializer.WriteObject(stream, dataToSend);
    request = Encoding.Default.GetString(stream.ToArray());
}
var client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.UploadStringCompleted += (sender, e) =>
{
    // make sure there's no error before trying to access the result
    if (e.Error == null)
    {
        string result = e.Result;
        // TODO: do something with the returned result here
    }
    else
    {
        // some error occurred => notify the UI
    }
};

client.UploadStringAsync(new Uri(tcAddress + "/Api/Audio/RegisterAudioThoughtUpload), request);

Also another problem I can see in the fiddler Response you have shown from the server is that the Content-Type header was set to application/json and yet the contents is not valid JSON:

"03cc77ed-e92b-48d9-b471-ba55a6065e2f"

instead of:

{"Data":"03cc77ed-e92b-48d9-b471-ba55a6065e2f"}

As far as the timeout error is concerned, maybe the response doesn't get to the phone. Check your network.

Upvotes: 1

Related Questions