HTTP POST multipart form-data

I’m working on an App in Xamarin.Forms. I want to send the Post Request to an API with form-data. In the code below, it returns the success message, but the data isn’t posted there.

public class Post {
    public string ConnectionId { get; set; }
    public string HolderFirstName { get; set; }
    }

public async void SendProof(object sender, EventArgs e) {
    try {
    Uri URL = new Uri(string.Format("http://11.222.333.44:4000/api/v1/Proof/SendProofNameRequest"));
    HttpClient _client = new HttpClient();

    var post = new Post {ConnectionId = "9c12dba2-6cb9-4382-8c96-f1708a7e8816", HolderFirstName = "Carl Dreyer"};
    var content = JsonConvert.SerializeObject(post);
    var response = await _client.PostAsync(URL, new StringContent(content, Encoding.UTF8, "multipart/form-data"));

    if (response.IsSuccessStatusCode) { 
    await DialogService.AlertAsync("Credential Proof Sent Successfully!");}
    }

    catch(Exception error) {
    await DialogService.AlertAsync(error.Message); }
    }

Binding for Button which triggers this Function.
public ICommand SendProofCommand => new Command(() => SendProof(default, default));

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

public async Task SendProof()
        {
            try {
                HttpClient client = new HttpClient(new NativeMessageHandler());
                client.BaseAddress = new Uri("http://11.222.333.44:4000/");
                var postData = new List<KeyValuePair<string, string>>();

                var nvc = new List<KeyValuePair<string, string>>();

                nvc.Add(new KeyValuePair<string, string>("ConnectionId", "9c12dba2-6cb9-4382-8c96-f1708a7e8816"));
                nvc.Add(new KeyValuePair<string, string>("HolderFirstName", "Bergman"));
                var req = new HttpRequestMessage(HttpMethod.Post, "http://11.222.333.44:4000/" + "api/v1/Proof/SendProofNameRequest") { Content = new FormUrlEncodedContent(nvc) };

                var res = await client.SendAsync(req);

                if (res.IsSuccessStatusCode)
                {
                    await DialogService.AlertAsync("Proof Sent Successfully!");
                }
                else
                {
                    await DialogService.AlertAsync("Unsuccessfull!");
                }
            }
            catch(Exception error) {
            await DialogService.AlertAsync(error.Message);
            }
        }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x