Ahad Rabu
Ahad Rabu

Reputation: 31

Pass string (json format) to WCF restful and get back string (json format)

I face a problem to pass a string which is formatted as json to a wcf restful service.

It gives me Http400 error. I don't know what's wrong.

Here's my code

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;
    }

Client's 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>");
}

Client's MyUser.cs

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

Upvotes: 1

Views: 1144

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

I see two problems:

  • You are not setting Content-Length of your request - web server will most probably reject your request with HTTP 400
  • Even if you set the Content-Length for the request your service will not be able to process it because it. First remove u from your UriTemplate - you are posting data and these data are in body of the message, not in uri. Next method parameter from string to UserAccount and let WCF to do deserialization automatically.

Upvotes: 1

Related Questions