Get Web Page HTML Content With Form Login

PHOTO EMBED

Mon Aug 22 2022 12:08:53 GMT+0000 (Coordinated Universal Time)

Saved by @HristoT #c#

// The inputFormFields
 var inputFormFields = new List<(string, string)>()
{
    (patientRecord.username, "username"),
    (patientRecord.password, "pass"),
};

// The Method
public async Task<(string, bool)> GetWebLabResultAsync(string url, List<(string fieldName, string fieldValue)> inputFormFields, Encoding pageEncoding = null)
{
   MultipartFormDataContent form = new MultipartFormDataContent();
   foreach (var field in inputFormFields)
   {
       form.Add(new StringContent(field.fieldName), field.fieldValue);
   }

   Uri myUri = new Uri(url, UriKind.Absolute);
   var pageResponse = await this.HttpClient.PostAsync(myUri, form);
   var pageSize = pageResponse.Content.ReadAsStringAsync().Result.Length;

   if (pageResponse.StatusCode != HttpStatusCode.OK || pageResponse.RequestMessage.Method == HttpMethod.Get)
    {
        return (string.Empty, false);
    }

    string htmlResult;
    if (pageEncoding == null)
    {
        htmlResult = await pageResponse.Content.ReadAsStringAsync();
    }
    else
    {
        var buffer = await pageResponse.Content.ReadAsByteArrayAsync();
        htmlResult = pageEncoding.GetString(buffer, 0, buffer.Length);
    }

    return (htmlResult, true);
}
content_copyCOPY