Ejemplo n.º 1
0
        public static Task <HttpResponseMessage> SendFormAsync(
            this HttpClient client,
            IHtmlFormElement form,
            IHtmlElement submitButton,
            IEnumerable <KeyValuePair <string, string> > formValues)
        {
            if (client is null)
            {
                throw new ArgumentNullException(nameof(client));
            }
            if (form is null)
            {
                throw new ArgumentNullException(nameof(form));
            }
            if (submitButton is null)
            {
                throw new ArgumentNullException(nameof(submitButton));
            }
            if (formValues is null)
            {
                throw new ArgumentNullException(nameof(formValues));
            }

            foreach (var kvp in formValues)
            {
                var element = form[kvp.Key];
                switch (element)
                {
                case IHtmlInputElement input:
                    input.Value = kvp.Value;
                    break;

                case IHtmlSelectElement select:
                    select.Value = kvp.Value;
                    break;
                }
            }

            Assert.True(form.CheckValidity(), "Form contains invalid data");
            var submit = form.GetSubmission(submitButton);

            var target = (Uri)submit.Target;

            if (submitButton.HasAttribute("formaction"))
            {
                var formaction = submitButton.GetAttribute("formaction");
                target = new Uri(formaction, UriKind.Relative);
            }

#pragma warning disable CA2000 // Dispose objects before losing scope
            var submision = new HttpRequestMessage(new HttpMethod(submit.Method.ToString()), target)
            {
                Content = new StreamContent(submit.Body)
            };
#pragma warning restore CA2000 // Dispose objects before losing scope

            foreach (var header in submit.Headers)
            {
                submision.Headers.TryAddWithoutValidation(header.Key, header.Value);
                submision.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            return(client.SendAsync(submision));
        }