How to send object as POST parameters to ASP.Net web request?

Viewed 8285

I'm trying to make web requests programmatically in ASP.NET, using the POST method. I'd like to send POST parameters with the web request as well. Something like this:

LoginData obj = new LoginData();
obj.OSVersion = deviceInformation.OperatingSystem;
obj.DeviceModel = deviceInformation.FriendlyName;
string URI = "https://XXXXXXXXX.azure-mobile.net/user/logsuserin";        
HttpWebRequest GETRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, UriKind.RelativeOrAbsolute));
GETRequest.Method = "POST";
GETRequest.ContentType = "application/x-www-form-urlencoded";
GETRequest.Headers["applicationKey"] = "UFakeKkrayuAeVnoVAcjY54545455544";
//GETRequest.Parameters.add(obj);

Obviously, the commented line does not work. How do I achieve this?

How to get a response by sending my obj as params?

Thanks in advance, Hemanth.

3 Answers

You need to use theGetRequestStream() method belonging to the HttpWebRequest

void Main()
{
    LoginData obj = new LoginData
    {
        Username = "foo",
        Password = "Bar"
    };

    byte[] objBytes = Encoding.UTF8.GetBytes(obj.ToString());

//    obj.OSVersion = deviceInformation.OperatingSystem;
//    obj.DeviceModel = deviceInformation.FriendlyName;
    string URI = "https://XXXXXXXXX.azure-mobile.net/user/logsuserin";
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, UriKind.RelativeOrAbsolute));
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.Headers["applicationKey"] = "UFakeKkrayuAeVnoVAcjY54545455544";
    request.ContentLength = objBytes.Length;

    using (Stream stream = request.GetRequestStream())
    {
        stream.Write(objBytes, 0, objBytes.Length);
    }

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using (Stream stream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }

}

public class LoginData
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string OSVersion { get; set; }
    public string DeviceModel { get; set; }
    public override string ToString()
    {
        var temp = this.GetType()
                       .GetProperties()
                       .Select(p => $"{p.Name}={HttpUtility.UrlEncode(p.GetValue(this).ToString())}");

        return string.Join("&", temp);
    }
}

If you want to use HttpClient:

using (var client = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Post, "https://XXXXXXXXX.azure-mobile.net/user/logsuserin");

    request.Headers.Add("applikationKey", "UFakeKkrayuAeVnoVAcjY54545455544");
    request.Content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("OSVersion", deviceInformation.OperatingSystem),
        new KeyValuePair<string, string>("DeviceModel", deviceInformation.FriendlyName),
    });

    var response = client.SendAsync(request).GetAwaiter().GetResult();
}

You can dynamically generate a FORM with "NameValueCollection". Using "NameValueCollection" you can add number of objects to be posted as -

NameValueCollection FormFields = new NameValueCollection();
        FormFields.Add("abc", obj1);
        FormFields.Add("xyz", obj2);
     Response.Clear();
    Response.Write("<html><head>");
    Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
    Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
    for (int i = 0; i < FormFields.Keys.Count; i++)
    {
        Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", FormFields.Keys[i], FormFields[FormFields.Keys[i]]));
    }
    Response.Write("</form>");
    Response.Write("</body></html>");
    Response.End();

OnLoad() of this form you can POST to desired URL.

Related