WP8 HttpWebRequest发布不起作用

时间:2013-09-20 18:02:43

标签: c# json wcf post windows-phone-8

我有一个Windows Phone应用程序而我正在尝试将JSON格式的数据发布到WCF应用程序。虽然建立了连接,但服务器返回带有

的自定义消息

这是C#代码:

ReportSightingRequest.Instance.Source = Source.IPhone;
var jsonData = JsonConvert.SerializeObject(ReportSightingRequest.Instance);
var uri = new Uri("urlGoesHere", UriKind.Absolute);

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = jsonData.Length;

string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
    using (var responseStream = response.GetResponseStream())
    {
        using (var sr = new StreamReader(responseStream))
        {
            received = await sr.ReadToEndAsync();
        }
    }
}

这是WCF接口:

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[Description("Description.")]
Response.Response ReportSighting(ReportSightingRequest sighting);

这是实施:

public Response ReportSighting(ReportSightingRequest sightingRequest)
{
    var response = new Response();
    if (sightingRequest == null || sightingRequest.TypeId == null)
    {
       response.Status = ResponseStatus.InvalidArguments;
       response.Message = "Request is null or no type has been supplied.";
       return response;
    }
...
}

当我从手机调用ReportSighting方法时,我收到“请求为空或没有提供类型”消息。奇怪的是,当我发送它时,我 AM 在WP8端发送TypeIdsightingRequest对象绝对不是空的。当我在jsonData上放置断点时,它包含了所有内容。 ReportSightingRequest对象也与WCF应用程序中的ReportSightingRequest完全相同。

这几乎感觉对象没有被序列化。这是我唯一能想到的。

有没有人有任何想法/建议?

更新

我注意到我实际上并没有发送对象。 Shawn Kendrot的答案似乎有意义但是当我整合他的代码时,它会返回 Not Found 错误。

更新 以下代码适用于控制台应用程序:

        var jsonData = "a hard coded JSON string here";
        var uri = new Uri("a url goes here", UriKind.Absolute);
        var webRequest = (HttpWebRequest)WebRequest.Create(uri);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/json; charset=utf-8";
        webRequest.ContentLength = jsonData.Length;

        webRequest.BeginGetRequestStream(ar =>
        {
            try
            {
                using (var os = webRequest.EndGetRequestStream(ar))
                {
                    var postData = Encoding.UTF8.GetBytes(jsonData);
                    os.Write(postData, 0, postData.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            webRequest.BeginGetResponse(
                ar2 =>
                {
                    try
                    {
                        using (var response = webRequest.EndGetResponse(ar2))
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            var received = reader.ReadToEnd();
                            //Console.WriteLine(received);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }, null);
        }, null);

更新 我在WP8中更改了我的代码以匹配Shawn Kendrot的解决方案。我在这里遇到的问题是我收到Not Found错误消息:

webRequest.BeginGetRequestStream(ar =>
            {
                try
                {
                    using (var os = webRequest.EndGetRequestStream(ar))
                    {
                        var postData = Encoding.UTF8.GetBytes(jsonData);
                        os.Write(postData, 0, postData.Length);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unsuccessful");
                }

                webRequest.BeginGetResponse(
                    ar2 =>
                    {
                        try
                        {
                            using (var response = webRequest.EndGetResponse(ar2))
                            using (var reader = new StreamReader(response.GetResponseStream()))
                            {
                                var received = reader.ReadToEnd();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Unsuccessful");
                        }
                    }, null);
            }, null);

我得到了:

{System.UnauthorizedAccessException:无效的跨线程访问。    在MS.Internal.XcpImports.CheckThread()    在MS.Internal.XcpImports.MessageBox_ShowCore(String messageBoxText,String caption,UInt32 type)    在System.Windows.MessageBox.ShowCore(String messageBoxText,String caption,MessageBoxButton按钮)    在System.Windows.MessageBox.Show(String messageBoxText)    在Notify.Logic.WebServices。&lt;&gt; c_ DisplayClass2.b _1(IAsyncResult ar2)    在System.Net.Browser.ClientHttpWebRequest。&lt;&gt; c_ DisplayClass1d.b _1b(Object state2)}

当我尝试做`MessageBox.Show(ex.Message);

更新

我已修复了MessageBox.Show错误消息的问题。

webRequest.Headers对象具有以下内容:

{Content-Type: application/json; charset=utf-8;}

1 个答案:

答案 0 :(得分:3)

您的目击请求为空,因为您没有发送任何数据。要使用WebRequest发送数据,您需要使用BeginGetRequestStream方法。此方法允许您打包数据。

var webRequest= (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = jsonData.Length;
webRequest.BeginGetRequestStream(ar =>
{
    try
    {
        using (Stream os = webRequest.EndGetRequestStream(ar))
        {
            var postData = Encoding.UTF8.GetBytes(jsonData);
            os.Write(postData, 0, postData.Length);
        }
    }
    catch (Exception ex)
    {
        // Do something, exit out, etc.
    }

    webRequest.BeginGetResponse(
        ar2 =>
        {
            try
            {
                using (var response = webRequest.EndGetResponse(ar2))
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    string received = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                // Do something, exit out, etc.
            }
        }, null);
}, null);