WindowsPhone HttpWebRequest 到 ashx WebService

WindowsPhone HttpWebRequest to ashx WebService

我对 HttpWebRequest 有疑问:

我在 visual studio ws 中有一个 ashx 代码,它只是:

public void ProcessRequest(HttpContext context)
    {
        var a = context.Request.Form["a"];
        var b = context.Request.Form["b"];
        context.Response.Write(a + " " + b);
    }

我尝试用 advancedRestClient 调用它并且它起作用了,但是如果我用我的 windows phone 设备调用它,我会得到一个未找到的异常并且请求没有到达任何断点。 这是我的 WP 代码:

    public void PostIt2()
    {

        string url = "http://localhost/blablacode/ecc.ashx";
        // Create a new HttpWebRequest object.
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.ContentType = "application/x-www-form-urlencoded";

        // Set the Method property to 'POST' to post data to the URI.
        request.Method = "POST";

        // start the asynchronous operation
        request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

        // Keep the main thread from continuing while the asynchronous
        // operation completes. A real world application
        // could do something useful such as updating its user interface. 
        allDone.WaitOne();
    }

    private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        Stream postStream = request.EndGetRequestStream(asynchronousResult);

        string postData = "{'a': 'avar','b':'bvar'}";

        // Convert the string into a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Write to the request stream.
        postStream.Write(byteArray, 0, postData.Length);
        postStream.Close();

        // Start the asynchronous operation to get the response
        request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
    }

    private static void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        Console.WriteLine(responseString);
        // Close the stream object
        streamResponse.Close();
        streamRead.Close();

        // Release the HttpWebResponse
        response.Close();
        allDone.Set();
    }

我从MSDN上拿了代码所以我不知道我做错了什么,我也尝试了很多在互联网上找到的方法,对我来说唯一重要的是我必须使用HttpWebRequest 而不是 HttpClient.

有人可以帮我吗?

可能问题不在代码中。 phone 可以访问您的服务吗? 您的项目是否配置了互联网接入?

如果一切正常,请看这个post:

好的,真的感谢上帝是星期五。 我用的是 url "localhost/eccecc.ashx"

设备的本地主机与计算机的本地主机不同。