0

我有一个非常简单的 ASP.NET Api 控制器,只有一种方法。

public HttpResponseMessage<User> Post(User user)
{
    return new HttpResponseMessage<User>(new User() { Name = "New User at Server" });
}

我的调试器说该方法已被调用,但问题是参数“user”的所有内容都设置为 null;我正在使用 Fiddler 来查看请求和响应.. 一切看起来都很好。

这是我在客户端的服务代码。

    public void AddUser(Models.User user, Action<Models.User> ShowResult)
    {
        var uiThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
        string url = "http://localhost:4921/User";
        Uri uri = new Uri(url, UriKind.Absolute);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        var sendWebPost = Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)
        .ContinueWith(task =>
            {
                Tuple<string, string>[] stringToSend = { Tuple.Create<string, string>("user", ObjectToJson<Models.User>(user)) };
                var bytesToSend = GetRequestBytes(stringToSend);   
                using (var stream = task.Result)
                    stream.Write(bytesToSend, 0, bytesToSend.Length);
            }
        ).ContinueWith(task => 
            {
                Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
                    .ContinueWith<WebResponse>(task2 => { ValidateResponse(task2); return task2.Result; })
                    .ContinueWith<Models.User>(task3 => {return JsonToObject<Models.User>(task3);})
                    .ContinueWith(task4 => { TryClearWorking(); ShowResult(task4.Result); }, uiThreadScheduler);
            });;


    }

    public static string ObjectToJson<T>(T obj) where T : class
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        MemoryStream stream = new MemoryStream();

        StreamReader sr = new StreamReader(stream);

        serializer.WriteObject(stream, obj);
        sr.BaseStream.Position = 0;
        string jsonString = sr.ReadToEnd(); 
        return jsonString;
    }


    protected static byte[] GetRequestBytes(Tuple<string, string>[] postParameters)
    {
        if (postParameters == null || postParameters.Length == 0)
            return new byte[0];
        var sb = new StringBuilder();
        foreach (var key in postParameters)
            sb.Append(key.Item1 + "=" + key.Item2 + "&");
        sb.Length = sb.Length - 1;

        return Encoding.UTF8.GetBytes(sb.ToString());
    }

谁能给我一些想法,从哪里开始寻找错误.....

4

1 回答 1

0

您需要设置 Content-Length 标头。

于 2012-05-14T11:41:28.873 回答