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

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.

Related

How to specify defaults for SwaggerResponse and SwaggerResponseExample?

Is there a way to specify the default response example in Swagger similar to the ProducesDefaultResponseType like this:
[ProducesDefaultResponseType(typeof(ProblemDetails))]
The Swagger attributes only seem to take the explicitly defined HTTP status codes:
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(ErrorExample), Description = "Error details")]
[SwaggerResponseExample(HttpStatusCode.BadRequest, typeof(ErrorExample))]
Is there a way to get Swagger recognize defaults instead of copying the same information for every HTTP response code?

if the request parameter header is as applicationx-www-form-urlencoded in json format how can i read it asp.net core

I set the Request header in postman as "application/x-www-form-urlencoded", and the format of the Request parameter is Json, but I can't get the value in asp.net core, I currently get request.form.keys.count () ==0 requset.body.length ==0 but requset.contentlength >0
I found the source of the problem, when I used routing matches like Controller/Action/id, I was unable to read the requested parameters
If I don't use it, I can read these parameters, and I suspect that this is a problem with the underlying code, and I can't solve it, so I don't use route matching, and I'm sad when I can't use route matching,I cannot get the requested parameters as follows=>
[Route("test/{str}")]
public async Task<IActionResult> test(string str)
{
return Content(str);
}

ShopStyle API - How to Invoke an HTTP request

How do I Invoke an HTTP request with a particular URL and process the body of the response as XML?
Information Provided by ShopStyle:
HOW TO USE THE API:
Choose the method that returns the data your application needs. For example, the /products method is used to get products that match a given category or brand.Construct a URL for that method with the appropriate host, method name, and query parameters. Invoke the URL as an HTTP GET.
When the HTTP response arrives, extract the required data elements from the response's body.The rest of this document describes the details of constructing the right URL for each of the API methods. The XML format of the responses may be seen by clicking on the sample URLs shown for each method. The responses in JSON format contain identical information, just in a different format.
SHOPSTYLE API URLS
All ShopStyle API URLs have the following form:
http://api.shopstyle.com/api/VERSION/METHOD_NAMEpid=YOUR_API_KEY&format=FORMAT&...
The METHOD_NAME is taken from the list of methods in the various API shown at left (Press Link To View List of Methods-https://www.shopstylecollective.com/api/overview).
COMMON API PARAMETERS
All methods in the API accept these parameters:
API_KEY (my unique key is ******************)
pid Unique API_KEY string that is assigned to the caller. You can find your API Key on the Account Settings page.
FORMAT
The format of the response. Supported values are:
json - The response is in JSON format with UTF-8 encoding. This is the default if the parameter is absent.
xml - The response is in XML format with UTF-8 encoding.
jsonp - The response is in JSON format with UTF-8 encoding wrapped in a JavaScript method called padding. The padding must be specified with the query parameter 'callback'. Only single expressions (function reference, or object property function reference) are accepted as valid padding.
When set to 1 or 'true' the HTTP status will always be 200. Use the field "errorCode" in the response to detect whether the API Call was successful. By default, when an error occur the HTTP Status of the response will be different than 200
Again I am a beginner, so please provide detailed information on how to retrieve CATEGORY data (Examples: Dresses, Tops, Buttoms, etc) in XML format.**
Thank you!!!
Here's a simple example to get your started. Copy the code below and put it into a file, say "cat.php". Then run it by typing "php cat.php" at a command prompt (assumes you have php on your machine):
<?php
// don't show dom parse errors
libxml_use_internal_errors(true);
// grab the xml from the api
$response = file_get_contents("http://api.shopstyle.com/api/v2/categories?pid=TEST&format=xml");
$doc = new DOMDocument();
$doc->loadHTML($response);
// grab all the categories
$elements = $doc->getElementsByTagName('categories');
foreach($elements as $node){
foreach($node->childNodes as $child) {
// get the name out of the category
$nodes = $child->getElementsByTagName("name");
foreach ($nodes as $name) {
echo $name->nodeValue . PHP_EOL;
}
}
}

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

Unable to add body to RestSharp RestRequest using enums

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.