I am using the below code to upload image with some additional parameters.
[HttpPost]
public HttpResponseMessage Upload(Data data)
{
var count = HttpContext.Current.Request.Files.Count;
return null;
}
I tried checked this method using postman chrome extension. I passed these values
Under Headers
enctype: multipart/form-data
Content-Type: application/json
Under form-data added one image file
Under raw
{
"Id": "1",
"ModifiedBy" : "1"
}
But the problem i am getting 0 for count
The Content-Type should be multipart/form-data not application/json for your code to work. A typical content type looks like this:
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvmxBBVAoH3KRsa9L
The actual post data then contains blocks of 'data' separated by the boundary. These blocks can contain a content type, but they don't have to. If you're doing file uploads the content type should not matter - the filename is what determines the type.
All that said, with WebAPI you shouldn't be using the ASP.NET HttpContext object, but rather the lower level Web API semantics. While what you're doing works as long as you run inside of the ASP.NET stack, if you self-host or maybe in the future run ontop of a different stack like OWin/Katana this code will no longer work.
To handle file uploads with Web API specific code check out this blog post from Filip W.
http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/
Related
My JSON request has a base value that is the top object.
Sample:
{
"partner_id": "6f4a3092-1b11-48c0-8a11-ae455b327ed8",
"borrowers": [
{
"loan": {
"loan_number": "89898989898222",
The partner_id is not being sent with the rest of the request.
Does this first object require special treatment to be sent with the rest of the request?
It feels like it should 'just work'
In my steps to file a bug, it started working in picking up the base object.
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);
}
I’ve been working on a simple function with the serverless framework that gets some data in a http POST, does some analysis and sends the results back. I got it working locally on my machine using serverless-offline but when it comes to deploying it I’m getting an error parsing the event.body.
Logging out the event.body it’s a string that looks like this:
----------------------------267253304929569989286258
Content-Disposition: form-data; name="text"
TEST
----------------------------267253304929569989286258--
so it makes sense that the parse is failing but I have no idea why this error it happening.
Any suggestions? I’ve tried a bunch of different things but am completely stumped.
Thanks in advance!
You can't JSON.parse that event.body cause it isn't JSON. It looks like whatever POSTed that data is using a multipart form POST style request rather than sending JSON. How are you invoking the HTTP POST?
I had the same issue and after a lot of debugging noticed 2 important things:
1.When the content type is application/x-www-form-urlencoded you might need to parse the data in a different way:
const qs = require('querystring');
module.exports.run = async event => {
try {
const data = qs.parse(event.body);
console.info('DATA:', data);
} catch(e) {
console.error(e.message);
}
}
2.When the Content-Type of the request is multipart/form-data the parsing will be even more complicated. I will suggest extra dependency to parse it like multiparty or any other of your choice
Thank you #Brian Winant! I am putting the answer here as a screenshot so it's clearer. In Postman, do the following:
AWS Lambda would return event.body as encoded query strings if the content-type is x-www-urlencoded. To have it return a JSON string you can then parse, send JSON data and set content-type as application/json.
I'm using JMeter 3.2.
My requirement is to read an XML file from the disk, replace some tags with dynamic values to ensure each thread sends a unique xml file upload (NOT SOAP Request). The following code in JSR223 sampler works perfectly fine when I try to upload the newfile through POST using a http sampler with ${newfilename} file text/xml.
import org.apache.commons.io.FileUtils;
try {
String content = FileUtils.readFileToString(new File("E:/test.xml"));
content = content.replaceAll("SUB_ID", "${__UUID}");
content = content.replaceAll("ABN_ID", "${empabn}");
content = content.replaceAll("EMPNAME", "${empname}");
vars.put("content", content);
FileUtils.writeStringToFile(new File("E:/testnew${empname}.xml"), content);
}
catch (Throwable ex) {
log.info("What happened?", ex);
throw ex;
}
Instead of writing again to the disk and uploading again, how can I send the contents of string 'content' as part of request body? I have looked at many posts that talk about the input output streams but they are confusing. When I try to send just ${content} in body, the application throws following error:
HTTP Status 500 - Could not write JSON: Name is null (through reference chain: com.xxx.xxx.datafile.rest.DataFileResponse["validationStatus"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Name is null (through reference chain:
Appreciate your help.
Multipart POST requests which are being used for files upload are different from normal POST requests hence there no possibility to simply substitute the file with the generated in-memory string.
You need to replicate the request exactly as it would be send by JMeter or real browser and manually populate each part starting from defining boundary using the HTTP Header Manager and ending up with the creation of Content-Disposition and specify your file contents there.
A little hint: you don't need to generate/substitute values for each call, it is enough to replace them once and JMeter will substitute them on its own given you use __eval() and __FileToString() functions combination.
You can check out Testing REST API File Uploads in JMeter for an example of creation a relatively complex file upload request, in your case it will be easier but still tricky.
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;
}
}
}