WindowsPhone HttpWebRequest到ashx WebService

时间:2015-07-24 12:35:46

标签: c# httpwebrequest ashx

我遇到了HttpWebRequest的问题:

我在视觉工作室中有一个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手机设备调用它,我会得到一个未找到的异常,并且请求没有到达任何断点。 这是我的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获取代码,所以我不知道我做错了什么,我也尝试了很多在互联网上找到的方法,对我来说唯一重要的是我必须使用{{1}而不是HttpWebRequest

有人能帮助我吗?

2 个答案:

答案 0 :(得分:0)

可能问题不在代码中。 您的服务可以通过手机访问吗? 您的proyect是否配置了Internet访问?

如果一切正常,请看这篇文章: httpclient postasync windows phone 8.1 universal app second call 404 error

答案 1 :(得分:0)

好的,非常感谢上帝星期五。 我正在使用url" localhost / eccecc.ashx"

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