Unable to add body to RestSharp RestRequest using enums - restsharp

I am using RestSharp in ASP .NET MVC 2 project. Trying to create RestRequest (using POST method) and add two enum values (my enum type -- OrderStatusFlags) to request body -- using build-in RestSharp XmlSerializer:
var request = new RestRequest("orders/{vendorID}/{number}", Method.POST);
request.AddBody(previousOrderStatus);
request.AddBody(newOrderStatus);
But after calling AddBody method in request parameters can see only empty but no value. And while calling MVC action method an error occurs:
The parameters dictionary contains a null entry for parameter 'previousStatus' of non-nullable type 'OrderStatusFlags' for method 'RestResponse PostOrderStatus(Int32, System.String, OrderStatusFlags, OrderStatusFlags)' in 'OrdersResourceEndpoint'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Enum look like this:
public enum OrderStatusFlags : long
{
Pending,
Confirmed,
...
}
Does anybody occurs a similiar situation?

A couple issues here. First, you can only call AddBody() once or the last call will take precedence. AddBody() is also only for sending XML as the request body. What is the required XML schema that you need to send to that URL? Can you post some sample XML that you're trying to generate?
I think more likely you actually want to use AddParameter() to add some POST parameters since that is far more common than XML request bodies.

Related

Testing API Post passing a <Frombody()> class - Always NULL

I am creating an api conroller class in VB. I have a very simple function in it:
Public Function Post(<FromBody()> ByVal value As String) As String
Return value
End Function
When I send a POST request from HTTP Tool (FireFox extension), I can see it go in the function, but value is always empty.
I have this in my WebApiConfig.vb:
config.Routes.MapHttpRoute(
name:="Names",
routeTemplate:="{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
And this in Global.ASAX.vb under Application-Start():
RouteTable.Routes.MapHttpRoute(name:="Post", routeTemplate:="post", defaults:=New With {.symbol = RouteParameter.Optional, .controller = "Names"})
I tried this from Fiddler 4 as well, but I get:
{"Message":"The request contains an entity body but no Content-Type
header. The inferred media type 'application/octet-stream' is not
supported for this resource.","ExceptionMessage":"No
MediaTypeFormatter is available to read an object of type 'String'
from content with media type
'application/octet-stream'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":"
at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent
content, Type type, IEnumerable '1 formatters, IFormatterLogger
formatterLogger, CancellationToken cancellationToken)\r\n at
System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage
request, Type type, IEnumerable '1 formatters, IFormatterLogger
formatterLogger, CancellationToken cancellationToken)"}
Or when I try to set the content-type in the header I get:
No MediaTypeFormatter is available to read an object of type 'String'
from content with media type ...
Where <...> is whatever media type I set.
How do I make this simple POST work?
It looks like the framework you are using for your API doesn't know how to parse the content of the body of your POST request based on the content type header that you are setting in your request.
Also, your API controller may not know how to parse plain text.
You can either manually add a supported content type, or read in the request content manually according to one of the answers in the above link. Or you can change your controller to accept a form post like so.

Jax rs optional header param

I am using dropwizard and jax rs to build my simple webapp. I read that all the query params specified in my method definition are optional and so are the HeaderParams. But here is where I am facing problem.
When I skip passing any query param, still the request is routed to the appropriate method. But when I skip passing header param, my request is not even routed to that method. Kindly help.
Example)
#GET
#Path(/sample)
Public Response getSample(#HeaderParam("header") final String header,
#QueryParam("query") final String query) {
}
In this sample, if I call this method with "header", this method gets invoked irrespective of whether I pass "query" param or not. At the same time, if I don't pass the "header", this method is not even getting invoked.
Also even if I give curl -H "header:" "http://localhost/sample?query=dummy" the request is not getting routed. I have to necessarily give a value for my header. Kindly help.
Note: I wrote down simplified representation of my code. Internally I am using dropwizard and swagger.
Thanks,
Sriram

MobileFirst - Answering a call to a WS (JAX-RS)

I have a java adapter (JAX-RS) that returns a POJO, one of the attributes is called validateUser and is a boolean value. I want to get the value of this boolean when called from main.js
It should work like this (main.js):
onGetLoginSuccess function (response)
busy.hide ();
alert ("validate:" + response ["validateUser"]);
As I can get the value in the variable response, the validateUser attribute my POJO.
Thank you for your attention
You can use alert(response.responseJSON.validateUser);
In general to examine the structure of "response" you could do something like: alert(JSON.stringify(response)); It could help you to understand which fields are available and how can you find this validateUser.
It is also important to make sure that your JAX-RS adapter returns JSON content type. Make sure that you have the annotation: #Produces("applicaion/json") in your JAX-RS method that returns this POJO

after receiving soap response modify xml and send to anther service using http adapter

while using http adapter I need to call first service that return XML,
after receiving the response I want to change values and send back to anther service,
how can I do it ?
do http adapter has json to xml function ?
WL adapter will automatically convert XML to JSON for you, however it doesn't have any manual JSON<->XML conversion APIs.
In your case possible solution might be to retrieve XML as plaintext by supplying returnedContentType:"plain" in invocation options. Alter whatever you need using regex/string replace. Use resulting string in 2nd procedure invocation as post body.
Alternatively, you can use 3rd party library to parse/convert/do whatever you need with XML, e.g. http://www.json.org/java/ (more info about how to use it in your adapter - http://public.dhe.ibm.com/software/mobile-solutions/worklight/docs/v506/04_08_Using_Java_in_adapters.pdf)
After checking number of solutions, I state the the http result will be a plain text,
then made a call to java function sending the xml as String, and used
javax.xml to hold and alter the XML.
XPath to retrieve the correct node using org.w3c.dom.*
Hope this will help you too.

Calling a webservice using google closures jsonp and sending json as parameter

I want to call a webservice using google closures, via jsonp since i am performing a cross domain webservice.
And i am calling it in the following manner
var url = "http://myurl/";
var jsonp = new goog.net.Jsonp(url);
jsonp.send(
{"name":"jessi","action":"initaction","gameId":"123"},
callback, callbackfailed);
But in this method the url is converted as a normal get method string as the follows
http://myurl/?name=jessi&action=initaction&gameId=123
But i need to send this url as a json object in the following manner
"name":"pari123","action":"initaction","gameId":"slotreel3"
How can i do this, i searched google and i couldnt find proper documentation regarding ?this.
The function goog.net.Jsonp.addPayloadToUri_ that is used to encode the object says:
#param {!Object} payload A map of value name pairs to be encoded.
A value may be specified as an array, in which case a query parameter
will be created for each value, e.g.:
{"foo": [1,2]} will encode to "foo=1&foo=2".
This is exactly what is happening. So, why not initialize your url with the query? e.g.
var url = "http://myurl.php?" + goog.json.serialize({"name":"jessi","action":"initaction","gameId":"123"});
var jsonp = new goog.net.Jsonp(url);
jsonp.send()
Untested but maybe this works.
Regards,
Rene