2

I am using a rest service to get back some json data. As a test harness, they gave me a url and if I go to the url in the browser, I have a form and i can put some json in a textarea and then submit the form and i get the json result back on the page reload.

I am now trying to replicate this programatically by using RestSharp in C# but i am running into an issue where the results from the call is the html of the page that i am going to (instead of the json result)

Here is my code:

var client = new RestClient {BaseUrl = new Uri("http://myhost.com:22333") };        

var request = new RestRequest { Method = Method.POST, Resource = "/site/api", RequestFormat = DataFormat.Json };

 request.AddBody(new
        {
            fieldtype = "name", value = "joe"
        });
        request.AddHeader("accept", "application/json");

        client.Authenticator = new NtlmAuthenticator();
        var response = client.Execute(request);
        var jsonDto = new JsonDeserializer().Deserialize<ResultObj>(response);

if i look at response.Content in the debugger (before any deserialization) i see an html string of the web page that i went to with the form to post (something like this)

<html>
<body>
<form method='POST'>
<table>
<tr>
<td>Enter the JSON:</td>
<td>
<textarea name="json_input" cols="80" rows="30">
</textarea>
</td>
</tr>
<tr><td colspan='2'><input type='Submit' value='submit'></td></tr>
</table>
</form>
</body>
</html>

Can someone advise what i am missing here as I am expecting to get the same json result back in response.Content that i see after submitting the form in the browser

8
  • What's the url when you post the form with data in test harness? Feb 9, 2016 at 3:39
  • If you can share the url and a sample json, we will be able to help.
    – Kosala W
    Feb 9, 2016 at 3:44
  • Please make sure that API method is POST(not GET or something else)
    – Thakur
    Feb 9, 2016 at 3:54
  • Please check that there is not an additional path needed beyond /api. E.g. site/api/customers Feb 9, 2016 at 4:04
  • @Guruprasad Rao - myhost.com:22333/site/Api
    – leora
    Feb 12, 2016 at 0:50

4 Answers 4

3
+400

The form has a text field named json_input that will be used as the request parameter.

<textarea name="json_input" cols="80" rows="30">

And your AddBody method indicated you are sending the request with fieldtype and value parameters.

Try replacing the AddBody method with the following:

request.AddBody(new { json_input = "{ fieldtype : \"name\", value : \"joe\"}" });

//OR

request.AddParameter("json_input",
                    "{ fieldtype : \"name\", value : \"joe\"}");
1

As seen in the HTML code, the action URL of the form will be waiting for the following form fields:

  • json_input

And in your code you are calling request.AddBody(new { ... }) that does the following:

  • As you set the RequestFormat to DataFormat.Json, the serializer to be used by default is JsonSerializer.
  • Content-Type header is setup to "application/json".
  • new { ... } will be serialized into a json string and AddBody() call is transformed into a call to AddParameter() using as parameter name "application/json", as parameter value the json string, and as parameter type ParameterType.RequestBody.

Using Fiddler2 you can see the POST made by your code:

code fiddler

As it is shown in the image, the request body is {"fieldtype":"name", "value":"joe"}, this may works if server is expecting the form fields fieldtype and value; but is expecting a request body like this json_input={ "fieldtype": "name", "value": "joe" } (decoded for clarity). In the next image, you can see the POST using the HTML:

html fiddler

Also, the type of the added parameter is ParameterType.RequestBody, so only the first body added using AddBody() function is used, the rest is discarded.

You can solve this problem by creating a Parameter called "json_input" and passing it to the function AddParameter():

var client = new RestClient { BaseUrl = new Uri("http://myhost.com:22333") };

var request = new RestRequest { Resource = "/site/api", RequestFormat = DataFormat.Json };

var param = new Parameter
{
    Type = ParameterType.GetOrPost,
    Name = "json_input",
    Value = new
    {
        fieldtype = "name",
        value = "joe"
    }
};

request.AddParameter(param);

client.Authenticator = new NtlmAuthenticator();

var response = client.Post(request);            

if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
    var deserializer = new JsonDeserializer();
    var jsonDto = deserializer.Deserialize<ResultObj>(response);
}

Using ParameterType.GetOrPost allows you to add as many parameters (form fields) as you want.

As you can see in my code, I added an if statement checking for HTTP StatusCode returned in the response because usually HTTP POST returns a 201 Created code.

You can add an else statement to check for the properties response.ErrorException and response.ErrorMessage to see what the problem is.

Perhaps, as the POST is not well formed, the server redirects you to the same page to try again.

0

Make sure to create a model based on what the API controller method expects. I have created an example using the info you provided, you will need to add all of the form fields to the model.

//Model for the data you are sending
public class TestModel
{
    public string Name { get; set; }
}

//define client, request and model
var client = new RestClient {BaseUrl = new Uri("http://myhost.com:22333") };        
var request = new RestRequest { Method = Method.POST, Resource = "/site/api", RequestFormat = DataFormat.Json };
var testModel = new TestModel() { Name = "joe" };

//serialize model as json and add it to the request
var json = request.JsonSerializer.Serialize(testModel);
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);

//execute request
IRestResponse response = client.Execute(request);

Make sure you are posting to the correct URI for the API.

Continue to inspect the HTML you receive and see if its giving you any errors.

Hope this helps.

-1

Try this:

var client = new RestClient {"http://myhost.com:22333/site/api"};        

var request = new RestRequest {  RequestFormat = DataFormat.Json };

 request.AddBody(new
        {
            fieldtype = "name", value = "joe"
        });

        client.Authenticator = new NtlmAuthenticator();
        var response = client.Post(request);
        if (response.StatusCode == HttpStatusCode.OK)
        {
            var jsonDto = new JsonDeserializer().Deserialize<ResultObj>(response);
1
  • this seems to do the same thing as my current code in the question
    – leora
    Feb 9, 2016 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.