如何将对象作为POST参数发送到ASP.Net Web请求?

时间:2017-09-26 06:15:17

标签: c# asp.net asp.net-web-api

我尝试使用POST方法在ASP.NET中以编程方式发出Web请求。 我也希望通过Web请求发送POST参数。像这样:

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);

显然,注释行不起作用。我如何实现这一目标?

如何通过将我的obj发送为params来获得响应?

提前致谢, Hemanth。

3 个答案:

答案 0 :(得分:1)

您需要使用属于GetRequestStream()

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);
    }
}

答案 1 :(得分:0)

如果您想使用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();
}

答案 2 :(得分:0)

您可以使用&#34; NameValueCollection&#34;动态生成FORM。使用&#34; NameValueCollection&#34;您可以添加要发布的对象数量 -

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()您可以POST到所需的URL。