0

Trying to send UrlEncoded form data in Post request :

        client.BaseAddress = new Uri("myURI");

        var formContent = new MultipartFormDataContent();
        formContent.Headers.ContentType.MediaType = "application/x-www-form-urlencoded";

        formContent.Add(new StringContent("password"), "grant_type");
        formContent.Add(new StringContent("someUser"), "username");
        formContent.Add(new StringContent("somePassword"), "password");
        HttpResponseMessage response = client.PostAsync("token", formContent).Result;

For some reason the request headers contain the following :

 somePassword
 --7e556624-1d60-4321-a4ee-a85f6ab601c6
 Content-Type: text/plain; charset=utf-8
 Content-Disposition: form-data; name=username

 someUser
 --7e556624-1d60-4321-a4ee-a85f6ab601c6
 Content-Type: text/plain; charset=utf-8
 Content-Disposition: form-data; name=password

etc...

The Guid I guess is a boundary. However since I used urlencode it should be a '?' boundary.

In fact, if I call my service with Postman, using the same parameters and application/x-www-form-urlencoded then the request headers contain :

app_profile=freelancer&username=someUser&password=SomePassword&grant_type=password

So how do I achieve this with C# ?

[EDIT]

I managed to make it work like this. However I'd like to understand what was wrong in the original code ?

 var values = new Dictionary<string, string>
        {              
            {"username", "someUser"},
            {"password", "somePassword"},
            {"grant_type", "password"},
        };

        var formContent = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json");
        HttpResponseMessage response = client.PostAsync("token", new FormUrlEncodedContent(values)).Result;

1 Answer 1

1

Initially, you used MultipartFormDataContent.

This means that Request content type will be replaced with multipart/form-data; boundary={some randomly generated key}

and the request body will be split in chunks using this {some randomly generated key} each chunk will have its own content type.

multipart/form-data content type especially useful when sending files together with other form data.

In the edited example, you are using StringContent

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for clarifying. It makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.