Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get form data from Postman To WebApi

I want to receive form data from Postman:

enter image description here

Content-Type: application/json

Here is WebApi method:

[HttpPost]
[Route("api/test")]
public async Task TestMethod(HttpRequestMessage request)
{
    var test = await request.Content.ReadAsStringAsync();
}

What I'm getting is:

------WebKitFormBoundarypqDvmeG89cBR9mK9
Content-Disposition: form-data; name="test"

esad
------WebKitFormBoundarypqDvmeG89cBR9mK9--

But I don't want data with WebKitFormBoundary and I've restriction to use formdata only. Is there any other way?

HTTP call information:

POST /api/test HTTP/1.1
Host: localhost:16854
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: 1a3d6427-4956-707d-da0c-3a29a63c7563

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="test"

esad
------WebKitFormBoundary7MA4YWxkTrZu0gW--

Curl call information:

curl -X POST \
  http://localhost:16854/api/test \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'postman-token: 02055873-e9a8-e9a6-019c-b407992b0e2f' \
  -F test=esad 
like image 923
Hina Khuman Avatar asked Aug 04 '18 08:08

Hina Khuman


People also ask

How to use postman to send an HTTP request to local API?

Let’s see how to use POSTMAN to send an HTTP request to our local ASP.NET Web API Services and check the response. Step 2: Once the Postman is successfully installed, open the Postman. It will look like the image shown below. Select the HTTP Method as “GET” and enter the URL of your Web API as shown in the below image.

How to get posted form data in an API controller?

To get posted form data in an API Controller (using the [ApiController] attribute) in ASP.NET Core, use parameters with the [FromForm] attribute. The form data is a string of key-value pairs (ex: location=United+States ).

What is the difference between get and post form methods?

The default method is GET. If the form uses GET, the form data is encoded in the URI as a query string. If the form uses POST, the form data is placed in the request body. For POSTed data, the enctype attribute specifies the format of the request body: Form data is encoded as name/value pairs, similar to a URI query string.

How do I send data from a form to an API?

Sending Form Data via AJAX When a user submits a form, the browser navigates away from the current page and renders the body of the response message. That's OK when the response is an HTML page. With a web API, however, the response body is usually either empty or contains structured data, such as JSON.


2 Answers

1) If you have to send Content-Type: multipart/form-data OR simply form-data

This is the first tab of Postman

enter image description here

If you have to collect only one key/value pair of your posted form-data

[HttpPost]
[Route("api/test")]
public HttpResponseMessage TestMethod(HttpRequestMessage request)
{
    var testValue = HttpContext.Current.Request.Form["test"];

    return Request.CreateResponse(HttpStatusCode.OK, testValue);
}

If you have to collect more than one key/value pair of your posted form-data

[HttpPost]
[Route("api/test")]
public HttpResponseMessage TestMethod(HttpRequestMessage request)
{
    NameValueCollection collection = HttpContext.Current.Request.Form;

    var items = collection.AllKeys.SelectMany(collection.GetValues, (k, v) => new { key = k, value = v });

    //We just collect your multiple form data key/value pair in this dictinary
    //The following code will be replaced by yours
    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();

    foreach (var item in items)
    {
        keyValuePairs.Add(item.key, item.value);
    }

    return Request.CreateResponse(HttpStatusCode.OK, keyValuePairs);
}

2) If you have to send Content-Type: application/x-www-form-urlencoded

This is the second tab of Postman

enter image description here

Then your API will be

[HttpPost]
[Route("api/test")]
public async Task TestMethod(HttpRequestMessage request)
{
    var test = await request.Content.ReadAsFormDataAsync();
}

Then you will get following output when you debug your code with breakpoint

enter image description here


3) If you have to send Content-Type: application/json

This is the third tab of Postman

See below screenshot for such option

enter image description here

And your api is

[HttpPost]
[Route("api/test")]
public async Task TestMethod(HttpRequestMessage request)
{
     var jObject = await request.Content.ReadAsAsync<JObject>();

     Item item = JsonConvert.DeserializeObject<Item>(jObject.ToString());
}

And your model to collect this posted data

public class Item
{
    public string test { get; set; }
}

And your output will be

enter image description here

The advantage of this option you can send complex type as posted data and like

enter image description here

And your api is

[HttpPost]
[Route("test")]
public async Task TestMethod(HttpRequestMessage request)
{
    var jObject = await request.Content.ReadAsAsync<JObject>();

    Sample sample = JsonConvert.DeserializeObject<Sample>(jObject.ToString());
}

And you model to collect this data are

public class Item
{
    public string test { get; set; }
}

public class Sample
{
    public Item item { get; set; }
}

And you will see the output is

enter image description here

like image 196
er-sho Avatar answered Oct 20 '22 04:10

er-sho


The following code will read key/value correctly when sent from Postman with form-data option selected

[HttpPost]
[Route("api/test")]
public async Task<HttpResponseMessage> TestMethod(HttpRequestMessage request)
{
    string root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);

    await Request.Content.ReadAsMultipartAsync(provider);

    var testValue = provider.FormData.GetValues("test")[0];

    return Request.CreateResponse(HttpStatusCode.OK);
}

A more thorough example can be found here (Section: Reading Form Control Data).

Edit: The HTTP call that is sent to the above API handler is the one below:

POST /api/stats/testmethod HTTP/1.1
Host: localhost:4100
Cache-Control: no-cache
Postman-Token: 999fd13d-f804-4a63-b4df-989b660bcbc5
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="test"

esad
------WebKitFormBoundary7MA4YWxkTrZu0gW--
like image 40
Tasos K. Avatar answered Oct 20 '22 03:10

Tasos K.