1

Have this :

 HttpContent requestContent = Request.Content;
 string jsonContent = requestContent.ReadAsStringAsync().Result;

then in this jsonContent :

ID=1234&toName=&fromId=49gjgijl7a4in

I am trying to parse in model :

 Model model = JsonConvert.DeserializeObject<Model>(jsonContent);

But it throws an exception :

Error parsing boolean value. Path '', line 0, position 0

Any idea ?

Edit :

My client side logic :

                var client = new HttpClient();
                var values = new Dictionary<string, string>()
                {
                    {"toId", obj.toId},
                    {"toName", obj.toName},
                    {"fromId", obj.fromId},
                };
                var content = new FormUrlEncodedContent(values);

                var response = await client.PostAsync(apiUrl, content);
                response.EnsureSuccessStatusCode();
activ8
  • 181
  • 3
  • 17

4 Answers4

1

To parse parameters from uri query string, use this from System.Web.HttpUtility

var content = Request.Content.ReadAsStringAsync().Result;
var query = HttpUtility.ParseQueryString(content);
var id = query.Get("ID");
var toName = query.Get("toName");
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
1

If you want to send data as Json objects use this code (client-side):

var client = new HttpClient();

var jsonObj = (dynamic)new JsonObject();
jsonObj.toId = obj.toId;
jsonObj.toName = obj.toName;
jsonObj.fromId = obj.fromId;

var content = new StringContent(jsonObj.ToString(), Encoding.UTF8, "application/json");

var response = await client.PostAsync(apiUrl, content);
            response.EnsureSuccessStatusCode();

Then you can use JsonConvert as in your question.

OR

If you want send data as query string but then use as Json:

var dict = HttpUtility.ParseQueryString(jsonContent);
var json = new JavaScriptSerializer().Serialize(
                    dict.AllKeys.ToDictionary(k => k, k => dict[k]));

Then you can use JsonConvert to deserialize it to your model.

OR

If you don't want to change client-side logic:

var dict = HttpUtility.ParseQueryString(jsonContent);

YourModel model = new YourModel()
{
    Id = dict.Get("ID"]),
    ToName = dict.Get("toName"),
    FromId = dict.Get("fromId")
};
Roman
  • 11,966
  • 10
  • 38
  • 47
0

Json Content Should be like this. Check you content

{ 
"ID":1234,
 "toName":"",
"fromId": "49gjgijl7a4in"
}
Damith Asanka
  • 934
  • 10
  • 12
0
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;

//you can split your jsonContent then you use the code
string[] paramsArrs = jsonContent.Split('&');`
Zubayer Bin Ayub
  • 310
  • 3
  • 11