Unable to pass NameValueCollection to POST WebAPI 5.0 core in ASP.NET / C#

Viewed 546

I am trying to pass NameValueCollection to ASP.NET Core 5.0 Web API controller (WebserviceController.cs) using HttpPost. I am trying to post 2 name values pairs as a sample: key1,value1 and key2,value2

C# (.NET Framework 4.8) Client code is:

webClient WebClient = new WebClient();
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
String response = Encoding.ASCII.GetString(webClient.UploadValues("https://localhost:44312/webservice", new NameValueCollection() { { "key1", "value1" }, { "key2", "value2" } }));

Postman screenshot:

Post Call

And I get error in C# client: The remote server returned an error: (415) Unsupported Media Type.

And in Postman:

Error

I tried the following 2 approaches to receive NameValueCollection to ASP.NET Core 5.0 Web API controller using HttpPost:

namespace Webservice.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WebserviceController : ControllerBase
    {
        [HttpPost]
        [Consumes("application/x-www-form-urlencoded")]
        public String Post([FromBody] NameValueCollection Values)
        {
            return "values received";
        }
    }
}

And:

public class classNameValueCollection
{
    public NameValueCollection SampleValues;
}

[ApiController]
[Route("[controller]")]
public class WebserviceController : ControllerBase
{
    [HttpPost]
    [Consumes("application/x-www-form-urlencoded")]
    public String Post([FromBody] classNameValueCollection Values)
    {
        return "values received";
    }
}

In the first one I am directly trying to get NameValueCollection in the Post method, and in the second approach I created a class that has a NameValueCollection variable and used the class object to receive NameValueCollection in Post method.

But I get the same error. What am I doing wrong here?

3 Answers

Instead of NameValueCollection and FromBody, use IFormCollection and FromForm

Reference Image

Tested with postman.

namespace Webservice.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WebserviceController : ControllerBase
    {
        [HttpPost]
        [Consumes("application/x-www-form-urlencoded")]
        public String Post([FromForm] Microsoft.AspNetCore.Http.IFormCollection Values)
        {
            string val1 = Values["key1"].ToString();
            string val2 = Values["key2"].ToString();
            return "values received";
        }
    }
}

You use wrong type in parameters, right way is

public String Post([FromForm] classNameValueCollection Values)
Related