null string parameter in body of POST request to WebAPI2 service - asp.net-web-api

I have an action defined in a WebAPI2 controller as follows:
[HttpPost]
[Route("DataImport/Product/")]
public DataImportJournalEntry ImportData([FromBody] string base64)
{
return _dataImportService.Import(Convert.FromBase64String(base64));
}
and I'm building a request, using RestSharp, as follows:
var base64 = {4Kb xml file loaded and encoded to base64}
var client = new RestClient(Config.BaseAddress);
var request = new RestRequest("DataImport/Product/", Method.POST);
request.AddParameter("base64", base64, ParameterType.GetOrPost);
request.AddHeader("accepts", "application/json");
var response = client.Execute<DataImportJournalEntry>(request);
The routing is correct as the action is called but the base64 parameter is null on the server side?

Found it..when using the FromBody attribute there can be only one parameter in the body and WebAPI is looking for it as ={value} not as you would expect {key}={value}. So I simply passed the parameter name as an empty string in the test:
...
var request = new RestRequest("DataImport/Product/", Method.POST);
request.AddParameter("", base64);
...
More details here: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Related

How to customize model in Springfox's Swagger 2 for a string request body?

I would like to customize the model for my API documentation I am making with Springfox's Swagger (Spring REST API).
This is an example for my code:
#ApiOperation("Creating a kafka topic")
#ApiImplicitParams(
#ApiImplicitParam(name = "requestBody", value = "The body of request", required = true,
example = "{\"server\": \"localhost:9092\",\"topic\": \"test\", \"parmas\":{...}}")
)
public ResponseEntity<String> createTopic(#RequestBody String requestBody) {
TopicCreationRequest request = gson.fromJson(requestBody, TopicCreationRequest.class);
...
return ResponseEntity.ok().body(response.toString());
}
Is it possible?
Thanks to Thomas__ I switched POJO and it work

How to convert from Java to Xamarin C#

Can someone help me convert the following from Java to C# (Xamarin)?
I tried a couple of different ways, but I cannot get it to work.
The code is:
HttpPost post = new HttpPost(url);
// Break out all extra HTTP header lines and add it to the HttpPost object
for (String line : contentType.replace("\r", "\n").split("\n")) {
if (line.length() > 0 && line.contains(":")) {
String[] parts = line.split(":", 2);
if (parts.length == 2) {
post.addHeader(parts[0].trim(), parts[1].trim());
}
}
}
// Create a byte array entity for the POST data, the content
// type here is only used for the postEntity object
ByteArrayEntity postEntity = new ByteArrayEntity(challenge);
postEntity.setContentType("application/octet-stream");
post.setEntity(postEntity);
// Create a HttpClient and execute the HttpPost filled out above
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(post);
// Get the response entity out of the response
HttpEntity entity = httpResponse.getEntity();
If you are stuck with
post.SetEntity(postEntity);
then it converts to:
ByteArrayEntity postEntity = new ByteArrayEntity(challenge);
postEntity.SetContentType("application/octet-stream");
post.Entity = postEntity;
When converting to Java from C# you mostly have to change the property names to start with upperCase and then if you get stuck on certain objects I would look check out the Xamarin API Docs, HttpPost class linked here.

What is the magento url for posting SOAP request

Below is my code
WebClient wc = new WebClient();
using(var response = wc.OpenRead("http://templatebar.com/QA/performancetesting/enterprise1_10_0_2/magento/index.php/api/v2_soap?wsdl=1"))
{
StreamReader sr = new StreamReader(response);
string result = sr.ReadToEnd();
}
var loginRequest = string.Format(XElement.Load(AppDomain.CurrentDomain.BaseDirectory + #"XMLFiles\login.xml").ToString(),"apikey","apipassword");var loginRequest = string.Format(XElement.Load(AppDomain.CurrentDomain.BaseDirectory + #"XMLFiles\login.xml").ToString(),"admin","abcd.1234");
var response1 = wc.UploadString("", loginRequest);
My question is what should be the "address" in UploadString function so that the login request gets the desired result i.e,Magento Session id
If I use this "http://templatebar.com/QA/performancetesting/enterprise1_10_0_2/magento/index.php/api/v2_soap?wsdl=1"
URL again then I get the list of wsdl services available,which is the same as in response variable.
Please Help,
Thanks.
According to the provided wsdl, the endpoint location is: http://templatebar.com/QA/performancetesting/enterprise1_10_0_2/magento/index.php/api/v2_soap/index/
(source: check the wsdl:service location for it. The url is written in the location-element)

Pass null String to Web API 2 (Visual Studio 2013)

I have a method like this:
public IEnumerable<Test> GetTest(Int32 idTest, String codTest, Int value)
and a test client like this:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await client.GetAsync("Test/GetTest/0/null/1/");
I need to pass null in the second parameter (that is not optional), but on server side I get a string with "null" inside and not the null value. I would not to put conversion functions for each parameter. I see that works if I put [FromBody] attribute to just one parameter, but if I set [FromBody] for all the string parameters I get internal server error.
Many thanks.
You typically shouldn't have optional parameters in the middle of a route.
I would recommend changing the order of your parameters, or add them as query parameters so they can be optional.
e.g. for http://example.com/Test/GetTest?a=0&b=&c=1
public IEnumerable<string> GetTest(Int32 idTest)
{
var queryPairs = Request.GetQueryNameValuePairs();
DoSomething(queryPairs);
...
}

How to retrieve photo previews in app.net

When I have an app.net url like https://photos.app.net/5269262/1 - how can I retrieve the image thumbnail of the post?
Running a curl on above url shows a redirect
bash-3.2$ curl -i https://photos.app.net/5269262/1
HTTP/1.1 301 MOVED PERMANENTLY
Location: https://alpha.app.net/pfleidi/post/5269262/photo/1
Following this gives a html page that contains the image in a form of
img src='https://files.app.net/1/60621/aWBTKTYxzYZTqnkESkwx475u_ShTwEOiezzBjM3-ZzVBjq_6rzno42oMw9LxS5VH0WQEgoxWegIDKJo0eRDAc-uwTcOTaGYobfqx19vMOOMiyh2M3IMe6sDNkcQWPZPeE0PjIve4Vy0YFCM8MsHWbYYA2DFNKMdyNUnwmB2KuECjHqe0-Y9_ODD1pnFSOsOjH' data-full-width='2048' data-full-height='1536'
Inside a larger block of <div>tags.
The files api in app.net allows to retrieve thumbnails but I somehow don't get the link between those endpoints and above urls.
The photos.app.net is just a simple redirecter. It is not part of the API proper. In order to get the thumbnail, you will need to fetch the file directly using the file fetch endpoint and the file id (http://developers.app.net/docs/resources/file/lookup/#retrieve-a-file) or fetch the post that the file is included in and examine the oembed annotation.
In this case, you are talking about post id 5269262 and the URL to fetch that post with the annotation is https://alpha-api.app.net/stream/0/posts/5269262?include_annotations=1 and if you examine the resulting json document you will see the thumbnail_url.
For completeness sake I want to post the final solution for me here (in Java) -- it builds on the good and accepted answer of Jonathon Duerig :
private static String getAppNetPreviewUrl(String url) {
Pattern photosPattern = Pattern.compile(".*photos.app.net/([0-9]+)/.*");
Matcher m = photosPattern.matcher(url);
if (!m.matches()) {
return null;
}
String id = m.group(1);
String streamUrl = "https://alpha-api.app.net/stream/0/posts/"
+ id + "?include_annotations=1";
// Now that we have the posting url, we can get it and parse
// for the thumbnail
BufferedReader br = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(streamUrl).openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(false);
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.connect();
StringBuilder builder = new StringBuilder();
br = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line=br.readLine())!=null) {
builder.append(line);
}
urlConnection.disconnect();
// Parse the obtained json
JSONObject post = new JSONObject(builder.toString());
JSONObject data = post.getJSONObject("data");
JSONArray annotations = data.getJSONArray("annotations");
JSONObject annotationValue = annotations.getJSONObject(0);
JSONObject value = annotationValue.getJSONObject("value");
String finalUrl = value.getString("thumbnail_large_url");
return finalUrl;
} .......

Resources