将字符串(json格式)传递给WCF restful并返回字符串(json格式)

时间:2012-04-23 06:18:30

标签: wcf wcf-rest

我面临一个问题,即将格式化为json的字符串传递给wcf restful服务。

它给我Http400错误。我不知道出了什么问题。

这是我的代码

IService.cs

[OperationContract]
    [WebInvoke(
        Method = "GET",
        UriTemplate = "savesomething/{u}",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    string SaveSomething(string u);

    [DataContract]
    public class UserAccount
    {
        [DataMember(Name = "userid")]
        public string UserId
        {
            get;
            set;
        }

        [DataMember(Name = "password")]
        public string Password
        {
            get;
            set;
        }
    }

Service1.cs

public string SaveSomething(string u)
    {
        UserAccount ua = Deserialize<UserAccount>(u);
        StringBuilder sb = new StringBuilder(string.Empty);
        sb.Append(string.Format("UserID : {0}\r\n", ua.UserId));
        sb.Append(string.Format("Password : {0}\r\n", ua.Password));
        File.WriteAllText(@"D:\\temp\data.txt", sb.ToString());
        return "completed!";
    }

    private static UserAccount Deserialize<UserAccount>(string json)
    {
        UserAccount obj = Activator.CreateInstance<UserAccount>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        obj = (UserAccount)serializer.ReadObject(ms);
        ms.Close();
        return obj;
    }

客户的default.cs

protected void Page_Load(object sender, EventArgs e)
{
    string serviceUrl = "http://localhost:65085/Service1.svc/savesomething";

    MyUser mu = new MyUser();
    mu.UserId = "bob";
    mu.Password = "bobbypassword";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl);
    request.Method = "POST";
    request.ContentType = "application/json; charset:utf-8";
    DataContractJsonSerializer seria = new DataContractJsonSerializer(mu.GetType());
    MemoryStream ms = new MemoryStream();
    seria.WriteObject(ms, mu);
    String js = Encoding.UTF8.GetString(ms.ToArray());
    StreamWriter write = new StreamWriter(request.GetRequestStream());
    write.Write(js);
    write.Close();
    HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
    StreamReader stReader = new StreamReader(resp.GetResponseStream());
    string jsonStr = stReader.ReadToEnd();
    resp.Close();
    Response.Write(jsonStr + "<BR>");
}

客户的MyUser.cs

public class MyUser
{
    public MyUser(){}
    public string UserId { get; set; }
    public string Password { get; set; }
}

1 个答案:

答案 0 :(得分:1)

我看到两个问题:

  • 您没有设置请求的内容长度 - 网络服务器很可能会拒绝您使用HTTP 400的请求
  • 即使您为请求设置了Content-Length,您的服务也无法处理它。首先从您的UriTemplate中删除u - 您正在发布数据,这些数据在消息正文中,而不是在uri中。从stringUserAccount的下一个方法参数,让WCF自动进行反序列化。